How to append to an array that is a value in a Swift dictionary

前端 未结 4 1862
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 16:00

Let\'s assume I have a dictionary that accepts a string as the key and an array as value:

var d = [String: [Int]]()
d[\"k\"] = [Int]()

Now I wo

4条回答
  •  借酒劲吻你
    2021-01-27 16:27

    Because Dictionary and Array are both struct types, you can't modify the Array in place, but instead have to extract and restore it:

    if var items = d["k"] {
        items.append(1)
        d["k"] = items
    }
    else {
        d["k"] = [1]
    }
    

提交回复
热议问题