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

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

    If the element for that key exists, you can simply do:

    d["k"]?.append(1)
    

    Note that if no element exists for the "k" key, then nothing happens. If you want to ensure there's actually an array for that key, just add this before appending:

    if d["k"] == nil {
        d["k"] = []
    }
    

提交回复
热议问题