Swift无法将字符串追加到使用字典查找的数组 [英] Swift Unable to Append String to an Array looked up with a dictionary

查看:50
本文介绍了Swift无法将字符串追加到使用字典查找的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道为什么此代码无法正常工作吗?

Any idea why this code is not working?

var apples = [String]()
var oranges = [String]()
var bananas = [String]()

var optionArrays : [String : [String]] = [
    "apple" : apples,
    "orange" : oranges,
    "banana" : bananas
]

optionArrays["apple"]!.append("Macintosh")
optionArrays["apple"]!.count // 1

apples.count // 0 -> Why isn't there already one apple?
apples.append("Golden Delicious")
apples.count // 1

由于某些原因, optionArrays ["apple"] 似乎可以正常工作,但没有实际的apples数组.这不行吗?

For some reason the optionArrays["apple"] seems to be working, but no the actual apples array. Shouldn't this work?

推荐答案

数组是swift中的值类型.当您将它们放入字典中时:

Arrays are value types in swift. When you put them into dictionaries:

var optionArrays : [String : [String]] = [
    "apple" : apples,
    "orange" : oranges,
    "banana" : bananas
]

创建

实际的 oranges bananas 数组的副本并将其放入字典中.修改字典时:

Copies of the actual apples, oranges and bananas arrays are created and put into the dictionary. When you modify the dictionary:

optionArrays["apple"]!.append("Macintosh")

您只能修改词典中副本.

一种解决方法是,每当修改字典时,将数组的所有副本分配给实际的数组:

A workaround is to assign all the copies of the arrays to the actual arrays whenever the dictionary is modfied:

var optionArrays : [String : [String]] = [
    "apple" : apples,
    "orange" : oranges,
    "banana" : bananas
    ] {
didSet {
    apples = optionArrays["apple"]!
    oranges = optionArrays["orange"]!
    bananas = optionArrays["banana"]!
}
}

另一种解决方法是为 Array 创建引用类型包装器:

Another workaround is to create a reference type wrapper for Array:

class RefArray<T> { // you can consider conforming to ExpressibleByArrayLiteral
    var innerArray = [T]()
}

var apples = RefArray<String>()
var oranges = RefArray<String>()
var bananas = RefArray<String>()

var optionArrays : [String : RefArray<String>] = [
    "apple" : apples,
    "orange" : oranges,
    "banana" : bananas
    ]

optionArrays["apple"]!.innerArray.append("Macintosh")
optionArrays["apple"]!.innerArray.count // 1

apples.innerArray.count

这篇关于Swift无法将字符串追加到使用字典查找的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆