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
Like this:
var d = [String: [Int]]()
d["k"] = [Int]()
if var items = d["k"] {
items.append(1)
d["k"] = items
}
You have to:
var
referenceThe if var
line does the first three steps all in one.
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]
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]
}
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"] = []
}