简体   繁体   中英

Swift: Accessing array value in array of dictionaries

I am currently struggling with obtaining a value from an array inside an array of dictionaries. Basically I want to grab the first "[0]" from an array stored inside an array of dictionaries. This is basically what I have:

var array = [[String:Any]]()
var hobbies:[String] = []
var dict = [String:Any]()

viewDidLoad Code:

dict["Name"] = "Andreas"
hobbies.append("Football", "Programming")
dict["Hobbies"] = hobbies
array.append(dict)

/// - However, I can only display the name, with the following code:

var name = array[0]["Name"] as! String
  • But I want to be able to display the first value in the array stored with the name, as well. How is this possible?

And yes; I know there's other options for this approach, but these values are coming from Firebase (child paths) - but I just need to find a way to display the array inside the array of dictionaries.

Thanks in advance.

If you know "Hobbies" is a valid key and its dictionary value is an array of String , then you can directly access the first item in that array with:

let hobby = (array[0]["Hobbies"] as! [String])[0]

but this will crash if "Hobbies" isn't a valid key or if the value isn't [String] .

A safer way to access the array would be:

if let hobbies = array[0]["Hobbies"] as? [String] {
    print(hobbies[0])
}

If you use a model class/struct things get easier

Given this model struct

struct Person {
    let name: String
    var hobbies: [String]
}

And this dictionary

var persons = [String:Person]()

This is how you put a person into the dictionary

let andreas = Person(name: "Andreas", hobbies: ["Football", "Programming"])
persons[andreas.name] = Andreas

And this is how you do retrieve it

let aPerson = persons["Andreas"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM