Swift泛型在使用继承时不会实例化泛型 [英] Swift Generics will not instantiate generic when using inheritance

查看:89
本文介绍了Swift泛型在使用继承时不会实例化泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类 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

必需的init(){} 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()


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泛型在使用继承时不会实例化泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆