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

前端 未结 4 1898
佛祖请我去吃肉
佛祖请我去吃肉 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: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 +=!(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]
    

提交回复
热议问题