Swift无法将字符串附加到使用字典查找的数组

时间:2017-02-13 07:40:36

标签: arrays swift

知道为什么这段代码无效?

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"]似乎正在工作,但没有实际的苹果数组。这不行吗?

2 个答案:

答案 0 :(得分:3)

数组是swift中的值类型。当你把它们放入词典时:

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

创建实际applesorangesbananas数组的副本并将其放入字典中。修改字典时:

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

您只修改字典中apples副本

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

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

另一种解决方法是为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

答案 1 :(得分:0)

因为Swift数组是值类型而不是引用类型

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

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

print("Initial values")
print(apples)
  

[]

print(optionArrays)
  

[“apple”:[],“orange”:[],“banana”:[]]

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

print("Values after update optionArrays")
print(apples)
  

[]

print(optionArrays)
  

[“apple”:[“Macintosh”],“orange”:[],“banana”:[]]

您会在此处看到apples array仅在更新optionArrays时未更新。因为swift的数组不是引用类型,所以它是值类型,因此apples将复制到optionArrays数组,因此optionArrays将单独更新。苹果也将单独更新。

所以apples.count将是0

现在尝试更新apple array值 apples.append(“金冠”) apples.count // 1

但现在optionArrays值与之前保持一致

print(optionArrays)
  

[“apple”:[“Macintosh”],“orange”:[],“banana”:[]]       optionArrays [ “苹果”]

print(apples)
  

[“Golden Delicious”]