加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:25:10 所属栏目:百科 来源:网络整理
导读: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"]]
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实例始终作为对现有实例的引用进行分配和传递,而不是作为副本传递. “

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读