swift字典嵌套数组操作 - 不能在嵌套字典内突变嵌套数组 [英] swift dictionary nested array manipulation - cannot mutate nested array inside dictionary
问题描述
var dict = ["alpha": ["a", "b", "c", "d"]]
// output : ["alpha": ["a", "b", "c", "d"]]
var alphaList = dict["alpha"]
// output : {["a", "b", "c", "d"]
alphaList?.removeAtIndex(1)
// output : {Some "b"}
alphaList
// output : {["a", "c", "d"]}
dict
// output : ["alpha": ["a", "b", "c", "d"]]
为什么'dict'没有改变?是因为alphaList是数组的副本,而不是字典中的实际数组?任何人都可以指出我在Swift语言文档中可以找到这些信息?
Why is 'dict' not altered? Is it because 'alphaList' is a copy of the array and not the actual array inside the dictionary? Can anyone point me where in Swift language documentation I can find this information?
什么是正确/功能的方式来操纵字典的值(复杂类型)? / p>
What is the correct/functional way to manipulate values (of complex type) of a dictionary?
推荐答案
好的问题是,它创建了您的案例中的值的副本,值为Array
Good question yes it creates the copy of the value in your case the value is Array
var alphaList = dict["alpha"]
/* which is the copy of original array
changing it will change the local array alphaList as you can see by your output */
output : {Some "b"}
要获得原始数组直接使用
In order to get the original array directly use
dict["alpha"]?.removeAtIndex(1)
或使用密钥更新它
alphaList?.removeAtIndex(1)
dict["alpha"] = alphaList
Apple:字符串,数组和字典的分配和复制行为
Swift的String,Array和Dictionary类型实现为结构。这意味着当字符串,数组和字典分配给一个新的常量或变量,或者当它们被传递给一个函数或方法时,它们将被复制。
Swift’s String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
与NSString,NSArray和NSDictionary在Foundation中不同,它们被实现为类而不是结构。 NSString,NSArray和NSDictionary实例总是作为对现有实例的引用分配和传递,而不是作为副本。
This behavior is different from NSString, NSArray, and NSDictionary in Foundation, which are implemented as classes, not structures. NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy. "
这篇关于swift字典嵌套数组操作 - 不能在嵌套字典内突变嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!