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
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]