简体   繁体   中英

Swift - Replace a value in a nested struct

I need to mutate nested dictionaries of unknown depth.

I realize that structs in swift are value types when in fact i would need a reference type ("NSMutable")

But I've noticed that if I access nested structs using dot(.) syntax I am able to update a value directly, without the need to reassign to the original "parent".

For instance In a case of nested arrays:

var l1 = ["a0","b0"]
var l2 = ["a1","b1"]
var list = [l1,l2]
print(list)
>>[["a0", "b0"], ["a1", "b1"]]


// I can mutate the nested structs by using dot(.) syntax
// mutate the zero indexed nested array:
list[0].insert("x0", atIndex: 0)
print(list)
>> [["x0", "a0", "b0"], ["a1", "b1"]]

// try to mutate after assignment - Not able to
var l1Ref = list[0]
print(l1Ref)
>> ["x0", "a0", "b0"]
l1Ref.removeFirst()
print(l1Ref)
>> ["a0", "b0"]
print(list)
// still the same as was before 
>> [["x0", "a0", "b0"], ["a1", "b1"]]

How can I mutate the nested struct iteratively without using dot syntax?

Arrays are structures in Swift and when you assignment a subarray to a variable you got a copy of the subarray. To get a reference to the subarray define type of your array as array of NSMutableArrays:

var array: [NSMutableArray] = [["a", "b", "c"]]
var subArray = array[0]
subArray.removeObjectAtIndex(1)

print(array, subArray)
>> [(a, c)] [(a, c)]

You can read more about Arrays in Swift here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM