Z.S.
Z.S.

Reputation: 49

How to obtain values without key of dictionary?

var dictionary: Dictionary<String, AnyObject>
    = ["title" : "Berlin",
       "description" : "Berlin square",
       "createdBy": "Mathias",
       "coordinates": ["fddfhsg": ["latitude": 56.34, "longitude": 53.44]]]

From the value at dictionary["coordinates"], I need to obtain the values for latitude and longitude, but I don't have the key of that dictionary ("fddfhsg").

(This key is generated by a Firebase database.)

Thanks for help.

Upvotes: 3

Views: 1754

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

You can get these values without knowing this key: cast "coordinates" to the right dictionary type then use optional binding and the values property.

Example:

if let dict = dictionary["coordinates"] as? [String:[String:Double]],
        content = dict.values.first,
        latitude = content["latitude"],
        longitude = content["longitude"] {
    print(latitude)
    print(longitude)
}

56.34
53.44


As an update after your comments: all you need to do now is to adapt to different dictionary structures.

For your second dictionary, look how it is structured:

for (key, value) in dictionary2 {
    print(key)
    print(value)
    print("---")
}

The values you're looking for are not at the same level than the other ones we grabbed previously.

Adapt the solution I've already given: it's only a matter of hierarchy in the dictionary. In dictionary1 the unknown key was in "coordinates", but this one is at the root level.

Upvotes: 6

Related Questions