dictionary - SWIFT dictionaries - Accessing a single value of a key with multiple values -
to access second value of second key of dictionary bellow:
this question not getting value of key, specific value if value array.
for following variable
var dict2 = ["key1" : "value1", "key2" : [ "value1" , "value2" ]]
this works (option 1)
let value2 = dict2["key2"]?[1] as? string println(value2!)
but not (option2)
let value2 = dict2["key2"][1]
other users suggested second option, not work. wandering why.
why should cast type? imagine if value int have cast int. assumes know type of value in there , exists. why calling optional?
since dictionary has different types values, have anyobject
type of value. you'll want cast type. also, dictionary accesses return optionals since key might not present in dictionary, you'll need unwrap value access it. finally, value array, use array index (1
access second item since array indices 0
based). here concrete example:
let dict = ["age" : 31, "names" : [ "fred" , "freddie" ]] if let val = dict["names"]?[1] as? string { println(val) // prints "freddie" }
since array index out of range crash program, safe want this:
if let array = dict["names"] as? [string] { if array.count > 1 { let name = array[1] println(name) } }
this style protects in following ways:
- if key
"names"
isn't in dictionary,if let
nothing instead of crashing. - if value isn't array of
string
thought was,if let
nothing. - by checking
array.count
first, ensures won't array index out of bounds error.
to add value "key2"
you'll need first explicitly give dictionary type [string: anyobject]
because type inferred swift nsdictionary
, type immutable, if declared var
.
var dict2:[string: anyobject] = ["key1" : "value1", "key2" : [ "value1" , "value2" ]] if let value = dict2["key2"] as? [string] { dict2["key2"] = value + ["value3"] }
Comments
Post a Comment