Home > Mobile >  How do I retrieve an item from an array that is inside a dictionary?
How do I retrieve an item from an array that is inside a dictionary?

Time:10-27

I'm trying to create a dictionary that has an array as the value of one of the dictionary items in Swift. I want to be able to retrieve a certain element in the array, but when I try to do it I get an error.

Here's my code:

var country = ["USA": [37.0902, 95.7129]]

let countrylatitude = country["USA"]
print(countrylatitude[0])

The error message was: Value of optional type '[Double]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Double]'

What does this mean? Thanks!

CodePudding user response:

Unwrapped basically means to check and make sure the value exists. countrylatitude possibly could be equal to nil because it doesn't know if "USA" is part of the dictionary.

There are multiple ways to unwrap to make sure it exists...

Force unwrap will crash if it is equal to nil

countrylatitude![0]

if let will only run if it can define a constant that is not equal to nil

if let latitude = countrylatitude {
     print(latitude[0])
}

guard let will not run any code after the guard statement unless it is not equal to nil

guard let latitude = countrylatitude else { return }
print(latitude[0])

Keep in mind that if the index of latitude[0] is not automatically assigned optional so if when you do countrylatitude[0] it is essentially just force unwrapping the index and it will crash if that index [0] does not exist.

  • Related