Swift泛型在使用继承时不会实例化泛型 [英] Swift Generics will not instantiate generic when using inheritance
问题描述
我有类 Alpha
和 Berry
:
class Alpha {}
class Berry:Alpha {}
我有一个在其泛型中使用继承的函数:
func myFunc< T:Alpha>(v:T) - > T {
return T()
}
我这样称呼myFunc:
myFunc(Berry())
在我的项目中,返回的对象类型为 Alpha
,而不是类型 Berry
。这是编译器中的一个错误,或者这只是我对泛型的误解? 解决方案
要传递一个实例的
Berry
并获取另一个 Berry
的实例? 如果是这样,下面的代码应该可以工作:
class Alpha {
init(){} //←你需要这个
func printme(){
println(我是alpha)
}
class Berry:Alpha {
override func printme(){
println(我是浆果)
}
}
func myFunc< T:Alpha>(v:T) - > T {
return v.dynamicType()
}
//这也适用:
/ *
func myFunc< T:Alpha>(v:T) - > T {
return(T.self as T.Type)()
}
* /
let a = myFunc(Berry())
a.printme()// - >我是berry
如果您想要将 I have classes I have a function that using inheritance within it's generic: I call myFunc like this: In my project, the object that gets returned is of type What you trying to achieve is passing an instance of If so, following code should work: If what you want is passing
这篇关于Swift泛型在使用继承时不会实例化泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!必需的init(){} $ c $为了确保从
Alpha
派生的所有类都有 init()
初始值设定项,c>是必需的。
这里是相关的Q / A: Swift泛型不保存类型 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()
Alpha
and Berry
:class Alpha { }
class Berry : Alpha { }
func myFunc<T : Alpha>(v:T) -> T {
return T()
}
myFunc(Berry())
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?Berry
and getting another instance of Berry
?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 typeBerry
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()