在Swift中将数据附加到全局数组

3

我在我的应用程序中创建了一个全局数组,并在不同的类中访问它,但是当我在不同的类中向数组附加数据时,我只得到了最后附加的数据。我的代码如下:

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)")

    }
}

当我运行代码时,我得到的结果是:
vehicles are Vehicle(name: "bike", location: "bangalore", price: "1.0", owner: "mark")

为什么我没有获得数组中的所有数据?为什么我只获取到最后一个附加的数据?请告诉我我做错了什么。

2
数组是值类型var VehicleInfo = GlobalArray.shared.collectionArray会创建一个数组的副本。你只能向该副本添加元素。 - Martin R
是的,我现在明白了。谢谢Martin。感谢您的回复。 - Manas Nayak
1个回答

1
您正在引用全局数组并向其添加内容,需要将其设置回去:
var VehicleInfo = GlobalArray.shared.collectionArray
VehicleInfo.append(Vehicle3)
GlobalArray.shared.collectionArray = VehicleInfo

或者简单地执行:
GlobalArray.shared.collectionArray.append(Vehicle3)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接