我遇到了问题,我找不到解决方案。
我有array
我存储不同对象的起始x和结束x位置
placedArray : [[String: [Int: [String: String]]]]
placedArray = [["auto": [0: ["x-start": "300", "x-end": "400"]]], ["bus": [0: ["x-start": "0", "x-end": "300"]]]]
我想在列表中再添加一个auto,所以我尝试做的是:
placedArray["auto"].append([1: ["x-start": "400", "x-end": "500"]])
错误:
不能使用'String'类型的索引下标'[[String:[Int:[String:String]]]]'类型的值
我想到最后
placedArray = [["auto": [0: ["x-start": "300", "x-end": "400"], 1: ["x-start": "300", "x-end": "400"]]], ["bus": [0: ["x-start": "0", "x-end": "300"]]]]
答案 0 :(得分:1)
两个问题:
Int
索引进行下标(这是错误消息的声明)。 auto
的值是字典,因此您无法append
。您必须获取placedArray
的第一项 - 这是auto
条目 - 然后设置密钥1
的值。
var placedArray : [[String: [Int: [String: String]]]]
placedArray = [["auto": [0: ["x-start": "300", "x-end": "400"]]], ["bus": [0: ["x-start": "0", "x-end": "300"]]]]
placedArray[0]["auto"]?[1] = ["x-start": "400", "x-end": "500"]
print(placedArray)
附加值的行也可以写为
placedArray[0]["auto"]?.updateValue(["x-start": "400", "x-end": "500"], forKey: 1)
然而,这种嵌套数组/字典非常混乱。一个(非常简单的)基于结构的解决方案怎么样:
struct XValue { let start, end : String }
struct Vehicle {
let name : String
var xValues : [XValue]
mutating func add(xValue : XValue) {
xValues.append(xValue)
}
}
var placedArray = [Vehicle(name: "auto", xValues: [XValue(start:"300", end: "400")]),
Vehicle(name: "bus", xValues: [XValue(start:"0", end: "300")])]
placedArray[0].add(xValue: XValue(start:"400", end: "500"))
print(placedArray)