我正在努力使用必须构建泛型类型的工厂方法。但是,它构造错误的类型。这是一个小代码示例:
class Vehicle : NSObject {
var numberOfWheels = 0
}
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
func construct<T : Vehicle>() -> T {
println("\(T.self.description())") //"__lldb_expr_964.Bicycle"
let newVehicle : T = T() // Here I expect a Bicycle to be created, but in fact a Vehicle is created
println("\(newVehicle.description)") //"<__lldb_expr_964.Vehicle: 0x7fd2abc1f810>"
return newVehicle
}
let a : Bicycle = construct()
println("\(a.numberOfWheels)") // '0'
如何告诉swift在'construct()'方法中创建一个Bicycle?
PS。一个有趣的观察是,如果我将类型参数的约束更改为<T : NSObject>
,则会创建一个自行车!