Swift:继承的对象

时间:2015-11-20 15:33:27

标签: ios swift2

当我使用派生类为基类作为参数的函数时,我收到一条奇怪的消息:

class Vehicle: Object, Mappable, Hashable, Equatable {
    ...
}

class Car: Vehicle {
    ...
}

class TransportFactory: NSObject{

    func doSomethingWithVehicles(vehicles:[Vehicle]){
    ...
    }

}

class CarFactory: TransportFactory{

    let myCars = [Car]()

    doSomethingWithVehicles(myCars)
} 

这导致:“无法将'[Car]'类型的值转换为预期的参数类型'[Vehicle]'”

Object是一个类(Realm),Mappable是一个协议(AlamofireMapper),Hashable和Equatable一个来自Foundation的协议

3 个答案:

答案 0 :(得分:0)

您在没有类型的情况下声明myCars,并为其指定了包含Array类的Car,因此类型推断实际上会为您提供一个Array,其中包含您的类对象。尝试:

let myCars = [Car]()
self.doSomethingWithVehicles(myCars)

这就是我更喜欢Array<Car>语法而不是[Car]的原因。我认为代码更清晰/更安全,因为let myCars = Array<Car>只是没有编译。

答案 1 :(得分:0)

你需要将doSomethingWithVehicles包装在一个函数中,你不能只是把它挂在类范围内:

class Vehicle: NSObject {
    //    ...
}

class Car: Vehicle {
    //    ...
}

class TransportFactory: NSObject {

    func doSomethingWithVehicles(vehicles:[Vehicle]){
        //        ...
    }

}

class CarFactory: TransportFactory {

    let myCars = [Car]()

    func someFunc() {
        self.doSomethingWithVehicles(myCars)
    }
}

myCars可以在类范围内,因为它是一个类变量。

答案 2 :(得分:0)

import Foundation

class Vehicle: NSObject{
}

class Car: Vehicle {
}

class TransportFactory: NSObject{

    func doSomethingWithVehicles(vehicles:[Vehicle]){
        print("Number of vehicles:", vehicles.count)
    }

}

class CarFactory: TransportFactory {

    let myCars = [Car]()

}

let carFactory = CarFactory()
carFactory.doSomethingWithVehicles(carFactory.myCars)
/* print out

Number of vehicles: 0

*/