'Swift: Array of Dictionaries get nested value

I'm need help in Swift, hope someone here can help me, I'm new and I don't understand exactly how to get values out of a nested JSON. this is what I have. In the example bellow I need to get "fullName" value out of this array can someone explain how would that work. I need to add it to and UILable. I really appreciate any help possible. thank you. Error is No exact match in call to superscript

    let worf : Array<NSDictionary> = [[
    "credentials": "<null>",
    "facultyImage": "https://cdn.atpoc.com",
    "fullName":"Deepak L. Bhatt, MD, MPH",
    "jobAffiliations": "Executive Director<br />Interventional Cardiovascular Programs<br />Brigham and Women&#8217;s Hospital<br />Heart &amp; Vascular Center<br />Professor of Medicine<br />Harvard Medical School<br />Boston, Massachusetts",
    "role": "Faculty"
]
  ,[
    "credentials": "<null>",
    "facultyImage": "https://cdn.atpoc.com",
    "fullName":"Javed Butler, MD, MPH",
    "jobAffiliations": "Professor of Medicine<br />Department of Medicine<br />University of Mississippi Medical Center<br />Jackson, Mississippi",
    "role": "Faculty"
  ]]

let myLists = [worf]

var myArray = [String]()
if let answersData = myLists["fullName"] as? String {
    for i in 0 ..< answersData.count{
        let result = answersData.values
        myArray.append(result)
    }
}
print("favorite drink:", myArray)
facultyCredentialsText.text = myArray.joined(separator: "\n")

enter image description here



Solution 1:[1]

There are some pretty serious mistakes:

  • worf is already an array [worf] makes it worse by adding another level.
  • You cannot subscript (not super-) an array.
  • fullName is a string, a loop makes no sense unless you want to iterate the characters.

And never use NSDictionary in Swift unless the compiler tells you to do it in some CoreFoundation APIs. Without the type annotation the compiler infers the array as [[String:STring]] which avoids the conditional downcast to String.

To get an array of all fullNames use something like

let worf = [[ ... ]]

let myArray = worf.compactMap{$0["fullName"]}
print("favorite drink:", myArray)
// avorite drink: ["Deepak L. Bhatt, MD, MPH", "Javed Butler, MD, MPH"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1