askaale
askaale

Reputation: 1199

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

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.

Upvotes: 4

Views: 8466

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

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"]

Upvotes: 2

vacawama
vacawama

Reputation: 154513

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])
}

Upvotes: 6

Related Questions