如何在没有字典键的情况下获取值?

Z.S*_*.S. 2 dictionary firebase swift

var dictionary: Dictionary<String, AnyObject> = ["title" : "Berlin",
"description" : "Berlin square",
"createdBy": "Mathias",
"coordinates": ["fddfhsg": ["latitude": 56.34, "longitude": 53.44]]]
Run Code Online (Sandbox Code Playgroud)

dictionary["coordinates"]

我需要获取纬度和经度值,但我不键入("fddfhsg")字典.此密钥由Firebase数据库生成.

感谢帮助.

aya*_*aio 6

您可以在不知道此键的情况下获取这些值:将"坐标"强制转换为正确的字典类型,然后使用可选绑定和values属性.

例:

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

56.34
53.44


作为评论之后的更新:您现在需要做的就是适应不同的字典结构.

对于您的第二本字典,请查看其结构:

for (key, value) in dictionary2 {
    print(key)
    print(value)
    print("---")
}
Run Code Online (Sandbox Code Playgroud)

您要查找的值与我们之前获取的其他值不同.

调整我已经给出的解决方案:它只是字典中的层次结构问题.在dictionary1未知密钥中是"坐标",但这个是在根级别.