gpt4 book ai didi

ios - Swift:将多个类型存储在一个数组中

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:33 26 4
gpt4 key购买 nike

如何在单个数组中存储多个类型?

我正在做以下事情:

var vehicles = [string]()
let mustang = Car() // car is a class name
mustang.brandName = "Ford"
mustang.modelName = "Mustang" // string type
mustang.modelYear = 1968
mustang.isConvertibible = true
mustang.isHatchback = false
mustang.hasSunroof = false // bool type
mustang.numberOfDoors = 2 // int type
mustang.powerSource = "gas engine"

// Add it to array
vehicles.append(mustang.brandName)
vehicles.append(mustang.modelName)
vehicles.append(mustang.modelYear) // Error: int type not supported
vehicles.append(mustang.isConvertibible) // Error: bool type not supported
vehicles.append(mustang.brandName)
vehicles.append(mustang.brandName)

我该如何实现?我是 Swift/iOS 的新手。

最佳答案

除了创建 string array,你还可以像这样创建 car 的 array 并直接存储 car 对象

var cars = [Car]()
let mustang = Car() // car is a class name
mustang.brandName = "Ford"
mustang.modelName = "Mustang" // string type
mustang.modelYear = 1968
mustang.isConvertibible = true
mustang.isHatchback = false
mustang.hasSunroof = false // bool type
mustang.numberOfDoors = 2 // int type
mustang.powerSource = "gas engine"
cars.append(mustang)

或者如果你想存储不同类型的object那么你不能创建AnyObjectarray,所以它会存储任何类型的该数组中的 instanceobject

var arr = [AnyObject]()
let car = Car()
let bike = Bike()
arr.append(car)
arr.append(bike)

关于ios - Swift:将多个类型存储在一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38388003/

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