swift 字典嵌套数组操作 - 无法改变字典内的嵌套数组

2024-04-28

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 语言文档中的哪里可以找到此信息?

操作字典的值(复杂类型)的正确/有效的方法是什么?


好问题,是的,它会在您的情况下创建值的副本,该值是数组

    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 : 字符串、数组和字典的赋值和复制行为 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_145

Swift 的 String、Array 和 Dictionary 类型都是作为结构体实现的。这意味着当字符串、数组和字典被分配给新的常量或变量,或者被传递给函数或方法时,它们会被复制。

这种行为与 Foundation 中的 NSString、NSArray 和 NSDictionary 不同,它们是作为类而不是结构实现的。 NSString、NSArray 和 NSDictionary 实例始终作为对现有实例的引用而不是副本进行分配和传递。 ”

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

swift 字典嵌套数组操作 - 无法改变字典内的嵌套数组 的相关文章

随机推荐