arrays - Swift 从包含类元素的数组中返回类型的对象

标签 arrays swift object generics subclass

这是我写的一小段代码来解释这个问题:

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/

相关文章:

mysql - 对在 mysql 查询中创建的对象数组内部进行排序

ios - 在没有建立连接的情况下无法确定接口(interface)类型 Xcode

c# - 非静态字段、方法或属性需要对象引用?

ios - 如何符合 MutableCollection?

c++ - C++将指针传递给对象的指针,无法访问成员

object - 如何查看对象数组中的特定属性

Java 字符串到字节

java - 初始化一个对象数组和初始化一个对象有什么区别?

arrays - 如何进行数组模式匹配

ios - WKWebView,将网页滚动到顶部