var dict = ["alpha": ["a","b","c","d"]] // output : ["alpha": ["a","d"]] var alphaList = dict["alpha"] // output : {["a","d"] alphaList?.removeAtIndex(1) // output : {Some "b"} alphaList // output : {["a","d"]} dict // output : ["alpha": ["a","d"]]
为什么’dict’没有改变?是因为’alphaList’是数组的副本而不是字典中的实际数组?任何人都可以指出我在Swift语言文档中哪里可以找到这些信息?
解决方法
好问题是它在您的情况下创建值的副本值为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"}
为了得到原始数组直接使用
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实例始终作为对现有实例的引用进行分配和传递,而不是作为副本传递. “