Reputation: 143
In my app I have created a global array and access it in different classes, but when I am appending data to the array in different classes, I am getting only the last appended data. My code is:
struct Vehicle {
var name: String
var location: String
var price: String
var owner: String
}
class GlobalArray {
static let shared = GlobalArray()
var Vehiclecollection = [Vehicle]()
}
class home{
func addVehicleOne(){
Vehicle1 = Vehicle(name: "Bus", location: "Delhi", price: "25.5", owner: "Bean")
var VehicleInfo = GlobalArray.shared.collectionArray
VehicleInfo.append(Vehicle1)
}
}
class addVehicle{
func addVehicleTwo(){
Vehicle2 = Vehicle(name: "car", location: "mumbai", price: "2.5", owner: "sean")
var VehicleInfo = GlobalArray.shared.collectionArray
VehicleInfo.append(Vehicle2)
addVehicleThree()
}
func addVehicleThree(){
Vehicle3 = Vehicle(name: "bike", location: "bangalore", price: "1.0", owner: "mark")
var VehicleInfo = GlobalArray.shared.collectionArray
VehicleInfo.append(Vehicle3)
print("vehicles are \(VehicleInfo)")
}
}
When I am running the code I am getting the result as:
vehicles are Vehicle(name: "bike", location: "bangalore", price: "1.0", owner: "mark")
Why am I not getting all the data in the array? Why am I getting only the last appended data? Please let me know what I am doing wrong.
Upvotes: 3
Views: 212
Reputation: 16341
You are making a reference to the global array and appending to it you need to set it back:
var VehicleInfo = GlobalArray.shared.collectionArray
VehicleInfo.append(Vehicle3)
GlobalArray.shared.collectionArray = VehicleInfo
or simply do:
GlobalArray.shared.collectionArray.append(Vehicle3)
Upvotes: 1