我不知道怎么样,如果有可能,编写方法来调用它的构造函数的泛型类型从普通已知的基类继承< T:基地>打造的T某些情况下不采取即与所有的钟声明确的工厂函数并通过类型推断提供口哨声。如何在swift中编写泛型工厂方法?
例,在游乐场工作:
// Let there be classes MyPod and Boomstick with common Base (not important)
class Base : Printable {
let value : String; init(_ value : String) { self.value = "Base." + value }
var description: String { return value }
}
class MyPod : Base {
init(_ value: String) { super.init("MyPod." + value) }
}
class Boomstick : Base {
init(_ value: String) { super.init("Boomstick." + value) }
}
// PROBLEM: do not know how to force call of Boomstick(n) instead of Base(n) in here
func createSome<T : Base>() -> T[] {
var result = Array<T>()
for n in 1...5 {
result += T(toString(n))
}
return result
}
// This seems to be fine.
// I was expecting call of createSome<Boomstick>() { ... result += Boomstick(n) ...
let objs : Boomstick[] = createSome()
// Prints: Base.1, Base.2, ... not much wished Boomstick.1, Boomstick.2, ...
println(objs)
一个显而易见的解决方案是创建委托给调用者,但似乎笨拙:
func createSome<T>(factory : (Int)->T) { ... }
谢谢。
PS:是不是createSome(分配) - >基础[]到OBJ文件:火枪[]类型安全违规?
可能重复的[Swift泛型不保留类型](http://stackoverflow.com/questions/26280176/swift-generics-not-preserving-type) – Lee