Swift Generics will not generate generic data when using inheritance
I have classes Alpha
and Berry
:
class Alpha { }
class Berry : Alpha { }
I have a function that uses inheritance within it generic:
func myFunc<T : Alpha>(v:T) -> T {
return T()
}
I call myFunc like this:
myFunc(Berry())
In my project, the returned object is of type Alpha
, not type Berry
. Is this a compiler bug or is it just something I don't understand about generics?
source to share
What are you trying to achieve is passing an instance from Berry
and getting another instance Berry
?
If so, the following code should work:
class Alpha {
required init() { } // ← YOU NEED THIS
func printme() {
println("I'm alpha")
}
}
class Berry : Alpha {
override func printme() {
println("I'm berry")
}
}
func myFunc<T:Alpha>(v:T) -> T {
return v.dynamicType()
}
// This also works:
/*
func myFunc<T: Alpha>(v:T) -> T {
return (T.self as T.Type)()
}
*/
let a = myFunc(Berry())
a.printme() // -> I'm berry
required init() { }
it is necessary that all classes derived from Alpha
have an init()
initializer. Here is a related Q / A: Swift generics non-persistent type
If you want to pass Berry
as a type and get a new instance Berry
try this:
class Alpha {
required init() { }
func printme() {
println("alpha")
}
}
class Berry : Alpha {
override func printme() {
println("berry")
}
}
func myFunc<T:Alpha>(v:T.Type) -> T {
return v()
}
let a = myFunc(Berry)
a.printme()
source to share