Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
askaale Avatar asked Oct 26 '25 20:10

askaale


1 Answers

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])
}
like image 174
vacawama Avatar answered Oct 29 '25 08:10

vacawama