必需的init(){} $ c $为了确保从 Alpha
派生的所有类都有 init()
初始值设定项,c>是必需的。
这里是相关的Q / A: p>
如果您想要将 Berry
作为类型传递并获取 Berry
,试试这个:
class Alpha {
required init ){}
func printme(){
println(alpha)
}
}
类Berry:Alpha {
override func printme() {
println(berry)
}
}
func myFunc< T:Alpha>(v:T.Type) - > T {
return v()
}
let a = myFunc(Berry)
a.printme()
I have classes Alpha
and Berry
:
class Alpha { }
class Berry : Alpha { }
I have a function that using inheritance within it's generic:
func myFunc<T : Alpha>(v:T) -> T {
return T()
}
I call myFunc like this:
myFunc(Berry())
In my project, the object that gets returned is of type Alpha
, and not of type Berry
. Is this is a bug in the compiler, or if this is simply something I'm misunderstanding about generics?
解决方案
What you trying to achieve is passing an instance of Berry
and getting another instance of Berry
?
If so, 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() { }
is necessary to ensure all classes derived from Alpha
have init()
initializer.Here is related Q/A: Swift generics not preserving type
If what you want is passing Berry
as a type and get new instance of 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()
这篇关于Swift泛型在使用继承时不会实例化泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!