Swift cannot append to subscript? -
i can't seem use .append() on subscript.
for example, here's array:
var arraytest = [ "test": 8, "test2": 4, "anotherarry": [ "test4": 9 ] ]
i able this:
arraytest.append(["test3": 3])
but can't append array inside arraytest. i'm trying:
arraytest["anotherarray"].append(["finaltest": 2])
first note: variable arraytest
dictionary of type [string: nsobject]
, not array. value key anotherarray
dictionary.
second note: setting key anotherarry
, retrieving key anotherarray
nil in example.
i'm not sure how able call append()
on arraytest
since dictionary , doesn't have method.
but key issue trying dictionaries , arrays value types , copied when passed around, rather referenced. when subscript arraytest
anotherarray
, getting copy of value, not reference value inside dictionary.
if want modify directly inside array or dictionary (as opposed replacing it), must reference type (a class). here's example of how code accomplished:
var arraytest = [ "test": 8, "test2": 4, "anotherarray": ([ "test4": 9 ] nsmutabledictionary) ] (arraytest["anotherarray"] as? nsmutabledictionary)?["test5"] = 10
note code forces "anotherarray" explicitly nsmutabledictionary
(a class type objective-c) instead of defaulting swift dictionary (a value type). that's makes possible modify outside dictionary, since being passed reference , not copied.
further note:
as pointed out in comments, using nsmutabledictionary not recommend , isn't pure swift solution, it's way arrive @ working example fewest changes code.
your other options include replacing anotherarray
value entirely modified copy instead of trying subscript directly, or if it's important able chain subscripts, create class wrapper around swift dictionary this:
class dictionaryreference<key:hashable, value> : dictionaryliteralconvertible, customstringconvertible { private var dictionary = [key : value]() var description: string { return string(dictionary) } subscript (key:key) -> value? { { return dictionary[key] } set { dictionary[key] = newvalue } } required init(dictionaryliteral elements: (key, value)...) { (key, value) in elements { dictionary[key] = value } } }
then use nsmutabledictionary example:
var arraytest = [ "test": 8, "test2": 4, "anotherarray": ([ "test4": 9 ] dictionaryreference<string, int>) ] (arraytest["anotherarray"] as? dictionaryreference<string, int>)?["test5"] = 10
Comments
Post a Comment