Swift - 在数组中插入数组

时间:2017-11-21 15:29:10

标签: swift

我遇到了问题,我找不到解决方案。 我有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"]]]]

1 个答案:

答案 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)