Swift - 替换嵌套结构中的值

时间:2015-10-19 15:43:39

标签: swift struct value-type subscript

我需要改变未知深度的嵌套词典。

我意识到swift中的结构是值类型,实际上我需要一个引用类型(" NSMutable")

但是我注意到如果我使用点(。)语法访问嵌套结构,我可以直接更新值,而无需重新分配给原来的父母"。

例如,在嵌套数组的情况下:

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

如何在不使用点语法的情况下迭代地改变嵌套结构?

1 个答案:

答案 0 :(得分:0)

数组是Swift中的结构,当你将一个子数组分配给一个变量时,你得到了一个子数组的副本。 要获得对子数组的引用,请将数组的类型定义为NSMutableArrays的数组:

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

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

您可以在Swift here

中阅读有关数组的更多信息