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

2024-01-18

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

dictionary["coordinates"]

我需要获取纬度和经度值,但我没有字典的键(“fddfhsg”)。该密钥由 Firebase 数据库生成。

感谢帮助。


您可以在不知道此键的情况下获取这些值:将“坐标”转换为正确的字典类型,然后使用可选绑定和values财产。

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


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

对于你的第二本字典,看看它的结构:

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

您正在寻找的值与我们之前获取的其他值不在同一水平。

适应我已经给出的解决方案:这只是字典中的层次结构问题。在dictionary1未知的键位于“坐标”中,但这个键位于根级别。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐