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

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

    0 讨论(0)
  • 2021-01-27 16:25

    All other answers are correct, but If you feel annoying to check nil, unwrap ...

    I made a custom operator.

    With this, you can unconditionally expand Optional arrays

    infix operator +=! {
        associativity right
        precedence 90
        assignment
    }
    
    func +=!<T, S:SequenceType where S.Generator.Element == T>(inout lhs:[T]?, rhs:S) {
        if lhs == nil {
            // the target is `nil`, create a new array
            lhs = Array(rhs)
        }
        else {
            // the target is not `nil`, just expand it
            lhs! += rhs
        }
    }
    

    Usage:

    var d = [String: [Int]]()
    
    // ... d["test"] may or may not exists ...
    
    d["test"] +=! [1]
    
    0 讨论(0)
  • 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]
    }
    
    0 讨论(0)
  • 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"] = []
    }
    
    0 讨论(0)
提交回复
热议问题