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

前端 未结 4 1857
佛祖请我去吃肉
佛祖请我去吃肉 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:07

    Like this:

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

    You have to:

    1. pull it out
    2. unwrap the Optional
    3. assign it to a var reference
    4. append, and
    5. put it back again

    The if var line does the first three steps all in one.

提交回复
热议问题