【发布时间】:2014-06-21 11:18:04
【问题描述】:
如果可能的话,我不知道如何编写调用其泛型类型的构造函数的方法,该构造函数继承自常见的已知基类
在操场上工作的示例:
// 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()->Base[] 赋值给 objs:Boomstick[] 类型不安全吗?
【问题讨论】:
标签: generics swift factory type-inference