I'm not sure how, if possible, to write a method that calls the constructor of its general type, inheriting from the common well-known base class <T: Base>, to create some instances of T without resorting to the explicit factory function, i.e. With all calls and whistles provided by type of output.
An example that works in a playground:
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) }
}
func createSome<T : Base>() -> T[] {
var result = Array<T>()
for n in 1...5 {
result += T(toString(n))
}
return result
}
let objs : Boomstick[] = createSome()
println(objs)
One obvious solution is to delegate the creation to the caller, but this seems awkward:
func createSome<T>(factory : (Int)->T) { ... }
Thank.
PS: Isn't createSome () β Base [] assigned to violate security rules like Boomstick []?
source
share