How to obtain values without key of dictionary?

前端 未结 1 988
清歌不尽
清歌不尽 2021-01-22 20:48
var dictionary: Dictionary = [\"title\" : \"Berlin\",
\"description\" : \"Berlin square\",
\"createdBy\": \"Mathias\",
\"coordinates\": [\"fddfh         


        
相关标签:
1条回答
  • 2021-01-22 21:25

    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.

    0 讨论(0)
提交回复
热议问题