在Swift中实例化一个泛型类型的对象 [英] Instantiate an object of a generic type in 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中运行代码片段,并观察 任何想法? :) 如果您将 它允许你使用一个不需要的初始化器来创建它一个bug。 I am implementing a class You can run the code snippet in an Xcode Playground and observe that Any Ideas? :) If you add The fact that it allows you to create it using an initializer that is not required is a bug. 这篇关于在Swift中实例化一个泛型类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! obj
类型为
SuperBar
而不是 Bar
,尽管它表示 Bar
当我 Alt - 点击常数名称。
所需的init(){}
添加到 SuperBar
,它工作正常。无论如何,这个需求总是需要的,因为你是从一个变量类创建一个实例。
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()
obj
is of type SuperBar
instead of Bar
, although it says Bar
when I Alt-click on the constant name.required init() { }
to SuperBar
, it works correctly. That requirement should always be required anyway because you are creating an instance from an variable class.