这是我写的一小段代码来解释这个问题:
class Vehicle{
var name:String = ""
var tyres: Int = 0
}
class Bus:Vehicle{
var make:String = "Leyland"
}
class Car: Vehicle{
var model:String = "Polo"
}
let myVehicles:[Vehicle] = [
Vehicle(),
Car(),
Bus()
]
for aVehicle in myVehicles{
if(aVehicle is Bus){
print("Bus found")
}
}
从代码中,我可以遍历并获取 Bus
类型的对象。但是,我需要一个函数来做同样的事情并返回该类型的元素(如果可用)。我尝试使用泛型,但它不起作用。我需要这样的东西:
func getVehicle(type:T.type)->T?{
// loop through the array, find if the object is of the given type.
// Return that type object.
}
最佳答案
将 foo 用作? T
尝试将 foo
转换为 T
类型。
for aVehicle in myVehicles{
if let bus = aVehicle as? Bus {
print("Bus found", bus.make)
}
}
您的 getVehicle
可以这样写:
func getVehicle<T>() -> T? {
for aVehicle in myVehicles {
if let v = aVehicle as? T {
return v
}
}
return nil
}
let bus: Bus? = getVehicle()
或功能上:
func getVehicle<T>() -> T? {
return myVehicles.lazy.flatMap { $0 as? T }.first
}
let bus: Bus? = getVehicle()
(请注意,我们需要将返回的变量指定为 Bus?
,以便 getVehicle
可以推断出 T
。)
关于arrays - Swift 从包含类元素的数组中返回类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42854206/