gpt4 book ai didi

arrays - 涉及数组声明的 Swift 字典

转载 作者:行者123 更新时间:2023-11-30 10:44:33 27 4
gpt4 key购买 nike

我无法访问字典中的数组。

print (fastWay["superMarket"][0])

各种声明类型已经过测试。

例如:

var fastWay: Dictionary<String, Any> = [:]

let roadMap = [
"home": ["hair": 5, "super": 10, "academy": 9],
"hair": ["home": 5, "super": 3, "bank": 11],
"superMarket":["hairShop":3, "home":10, "englishAcademy":7, "restaurant":3],
"englishAcademy": ["home":9, "superMarket":7, "school":12],
"restaurant" : ["superMarket":3, "bank":4],
"bank" : ["hairShop":11, "restaurant":4, "englishAcademy":7, "school":2],
"school" : ["bank":2, "englishAcademy":12]]

print (roadMap["home"]?["academy"])

var fastWay: Dictionary<String, Any> = [:]
for i in roadMap.keys{
fastWay.updateValue([false, 9999, "start"], forKey: i)}

print (fastWay)
print (fastWay["superMarket"][0])

Xcode Playground 评论:可选类型“任何?”的值必须解包才能引用包装基类型“Any”的成员“下标”

最佳答案

由于字典中的值是 Any 类型,因此无法访问下标,因为编译器无法知道该值类型是否可以处理它。

您只需将值类型转换为对象数组,然后就可以访问它们:

var fastWay: Dictionary<String, Any> = [:]
for i in roadMap.keys{
fastWay.updateValue([false, 9999, "start"], forKey: i)
}

print (fastWay)

if let parsed = fastWay["superMarket"] as? [Any] {
//access any value you want
print(parsed[0])
}

关于arrays - 涉及数组声明的 Swift 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56031585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com