swift dictionary嵌套数组 *** 作 – 不能在字典中改变嵌套数组

swift dictionary嵌套数组 *** 作 – 不能在字典中改变嵌套数组,第1张

概述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 "
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实例始终作为对现有实例的引用进行分配和传递,而不是作为副本传递. “

总结

以上是内存溢出为你收集整理的swift dictionary嵌套数组 *** 作 – 不能在字典中改变嵌套数组全部内容,希望文章能够帮你解决swift dictionary嵌套数组 *** 作 – 不能在字典中改变嵌套数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/998916.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存