I am not sure how to, if it's possible to, write method that calls constructor of it's generic type inheriting from common known base class < T:Base > to create some instances of T without resorting to explicit factory function i.e. with all bells and whistles provided by type inference.
Example that works in playground:
// 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)
One obvious solution is to delegate creation to caller, but that seems clunky:
func createSome<T>(factory : (Int)->T) { ... }
Thank you.
PS: Isn't assignment of createSome()->Base[] to objs:Boomstick[] type safety violation?