fs_tigre fs_tigre - 3 months ago 10
Swift Question

How to update merged array after one is being updated in Swift

In the following example, how can I make

mix
to update to reflect changes made to any of the merged arrays?

var fruits = ["Apple", "Orange", "Bannana"]
var cars = ["Cobalt", "Durango", "Jetta"]

var mix = fruits + cars

print(fruits)
print(cars)

print(mix)

cars.append("Mustang") // cars array modification

print(mix) // how to update mix to show Mustang?


IBM Sandbox:
http://swiftlang.ng.bluemix.net/#/repl/57c973068254a18716900079

Answer

Computed variable is what are you looking for, I believe:

var fruits = ["Apple", "Orange", "Bannana"]
var cars =  ["Cobalt", "Durango", "Jetta"]

var mix: [String] {return fruits + cars}

print(mix)
//["Apple", "Orange", "Bannana", "Cobalt", "Durango", "Jetta"]

cars.append("Mustang") // cars array modification
print(mix)
//["Apple", "Orange", "Bannana", "Cobalt", "Durango", "Jetta", "Mustang"]