Arrays are value types in swift. When you put them into dictionaries:
var optionArrays : [String : [String]] = [
"apple" : apples,
"orange" : oranges,
"banana" : 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")
you only modify the copy of apples that is in the dictionary.
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"]!
}
}
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
applesarray. You did it for theoptionsArrays.