4

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.

1
  • But I want to be able to display the first value in the array stored with the name?? u mean with key and value?? Commented Jun 13, 2016 at 10:54

2 Answers 2

6

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])
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Just what I needed! Thank you very much! :-)
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.