在Swift中实例化一个泛型类型的对象 [英] Instantiate an object of a generic type in Swift

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

问题描述

我在Swift中实现了一个类 Foo ,它应该实例化给定子类的对象 SuperBar ,例如 Bar:SuperBar 。我非常喜欢Swift中的泛型,所以我试着用这种方式实现它:

  class Foo< T:SuperBar> {

func instantiateObject() - > T {
return T()
}

}

class SuperBar {

}

class Bar:SuperBar {

}

let foo = Foo< Bar>()

let obj = foo.instantiateObject()

您可以在Xcode Playground中运行代码片段,并观察 obj 类型为 SuperBar 而不是 Bar ,尽管它表示 Bar 当我 Alt - 点击常数名称。

任何想法? :)

解决方案

如果您将所需的init(){} 添加到 SuperBar ,它工作正常。无论如何,这个需求总是需要的,因为你是从一个变量类创建一个实例。

它允许你使用一个不需要的初始化器来创建它一个bug。


I am implementing a class Foo in Swift, that is supposed to instantiate objects of a given subclass of SuperBar, e.g. Bar: SuperBar. I really like generics in Swift, so I tried implementing it this way:

class Foo<T: SuperBar> {

    func instantiateObject() -> T {
        return T()
    }

}

class SuperBar {

}

class Bar: SuperBar {

}

let foo = Foo<Bar>()

let obj = foo.instantiateObject()

You can run the code snippet in an Xcode Playground and observe that obj is of type SuperBar instead of Bar, although it says Bar when I Alt-click on the constant name.

Any Ideas? :)

解决方案

If you add required init() { } to SuperBar, it works correctly. That requirement should always be required anyway because you are creating an instance from an variable class.

The fact that it allows you to create it using an initializer that is not required is a bug.

这篇关于在Swift中实例化一个泛型类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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