我这样设置一个数组:
let modelArray = [
"Casual": ["health": 17, "weapon": 8, "crafting": 15, "social": 30],
"Soldier": ["health": 25, "weapon": 32, "crafting": 8, "social": 5],
"Doctor": ["health": 35, "weapon": 5, "crafting": 15, "social": 15],
"Dorothy": ["health": 15, "weapon": 15, "crafting": 20, "social": 20],
"Asian": ["health": 13, "weapon": 5, "crafting": 7, "social": 45],
"Police": ["health": 23, "weapon": 22, "crafting": 5, "social": 20]
]
如何在循环时访问 String(例如“Casual”)值?
for (index, model) in character.modelArray.enumerate()
{
print("\(index) carries: \(model[0]")
}
这给了我Type '(String, Dictionary)' has no subscript members
最佳答案
正如 Josh 所指出的,您的 modelArray
对象是字典的字典。 (let modelArray : [String: [String:Int]]
是完整的类型信息)。
其中的字典不能使用 Int
进行下标,只能使用 String
。
这是您的代码的一个版本,它将获取每个角色的一些健康状况:
for statDictionary in characters.modelArray {
let health = statDictionary["health"]
print(health)
}
进一步的建议
出于某些目的,将这样的数据存储在字典中是可行的,但您可能会发现可以通过创建用于保存此状态信息的结构(或类)来创建更清晰、更安全的 API。
struct CharacterStats {
let health : Int
let weaponNumber : Int
// etc.
}
然后枚举会更简单,并且不需要松散的字符串键(可能会打错)。
for stat in characters {
let health = stat.health
}
关于数组中的 iOS Swift 访问字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38806728/