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//
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语言文档中哪里可以找到这些信息?
操纵字典值(复杂类型)的正确/功能方法是什么?
好问题是它在您的情况下创建值的副本值为Arrayvar 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"}
为了得到原始数组直接使用
dict["alpha"]?.removeAtIndex(1)
或者使用密钥更新它
alphaList?.removeAtIndex(1) dict["alpha"] = alphaList
Apple:Assignment and Copy Behavior for Strings, Arrays, and Dictionaries
Swift的String,Array和Dictionary类型实现为结构.这意味着字符串,数组和字典在分配给新常量或变量时或者传递给函数或方法时会被复制.
此行为与Foundation中的NSString,NSArray和NSDictionary不同,它们实现为类,而不是结构. NSString,NSArray和NSDictionary实例始终作为对现有实例的引用进行分配和传递,而不是作为副本传递. “