【问题标题】:Swift return object of type from an array containing class elements从包含类元素的数组中快速返回类型的对象
【发布时间】:2017-03-17 09:50:40
【问题描述】:

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

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.
}

【问题讨论】:

    标签: arrays swift object generics subclass


    【解决方案1】:

    使用foo as? 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。)

    【讨论】:

    • 那么,我不必为此方法指定任何类类型?
    • @Nareshkumar。该方法是通用的。使用哪种类型的车辆是从分配给它的变量的类型推断出来的。请参阅 kennytm 写的 let bus: Bus? = getVehicle() 而不仅仅是 let bus = getVehicle()。是 bus 的显式类型选择了正确的 T
    【解决方案2】:

    你可以这样写:

     func getVehicle<T>(type:T)-> [T]{
        return myVehicles.filter{ $0 is T }.map{$0 as! T }
     }
    

    【讨论】:

      【解决方案3】:

      你也可以这样用:

      func getVehicle<T>(type: T.Type) -> T? { return myVehicles.filter { type(of: $0) == type }.first as? T }

      用法:

      getVehicle(type: Bus.self)

      【讨论】:

        【解决方案4】:

        你也可以这样用:

        let a = array.compactMap({ $0 as? MyTypeClass })
        // a == [MyTypeClass] no optional 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-20
          • 1970-01-01
          • 2020-09-28
          • 1970-01-01
          • 1970-01-01
          • 2018-06-02
          相关资源
          最近更新 更多