fs_tigre
fs_tigre

Reputation: 10748

Access items from an Array that is inside a Dictionary in Swift

I have a Dictionary which contains an array of fruits and a Double. What I would like to be able to do is access the fruits inside the array.

How can I access items inside the fruits array?

var fruits =  ["Apple", "Oranges"]

var fruitDictionary:[String: Any] = ["fruits":fruits, "car":2.5]

print("Dictionary: \(fruitDictionary["fruits"]!)") // output: Dictionary: ["Apple", "Oranges"]

I tried...

print("Dictionary: \(fruitDictionary["fruits"[0]]!)")

and...

print("Dictionary: \(fruitDictionary["fruits[0]"]!)")

But no luck

Thanks

Upvotes: 1

Views: 110

Answers (1)

nathangitter
nathangitter

Reputation: 9795

First you need to access the fruits entry of the dictionary and cast it as an array of strings.

From there you can access the elements of the array.

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

The reason why your attempts did not work is because the values in your dictionary are of type Any, which might not be able to be accessed through a subscript.

Upvotes: 2

Related Questions