gpt4 book ai didi

arrays - 将数据附加到 Swift 中的全局数组

转载 作者:行者123 更新时间:2023-12-04 04:09:52 25 4
gpt4 key购买 nike

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

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

为什么我没有得到数组中的所有数据?为什么我只得到最后附加的数据?请让我知道我做错了什么。

最佳答案

您正在引用全局数组并附加到它,您需要将其设置回去:

var VehicleInfo = GlobalArray.shared.collectionArray
VehicleInfo.append(Vehicle3)
GlobalArray.shared.collectionArray = VehicleInfo

或者简单地做:

GlobalArray.shared.collectionArray.append(Vehicle3)

关于arrays - 将数据附加到 Swift 中的全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61907773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com