gpt4 book ai didi

swift - 在通用元类型函数中返回具有特定元类型的对象

转载 作者:行者123 更新时间:2023-11-30 13:23:58 24 4
gpt4 key购买 nike

我对继承和泛型类有一些问题。我想在函数中返回子类的对象(具有特定的泛型类型),该函数返回具有泛型元类型的父类的对象。

或多或少,我有这样的类和函数结构:

class Element {}
class Item:Element {}

class A<aType:Element> { }
class B:A<Item> { }

class SomeClass {
func foo() -> A<Element> {
return A<Element>()
}
}
class OtheClass:SomeClass {
override func foo() -> A<Element> {
return B() // An error where!
}
}

我不能做的是在OtherClass的foo函数中return B()。错误是:

Cannot convert return expression of type 'B' to return type 'A< Element >'

有什么办法吗?

最佳答案

我找到的解决方案是:

class CoreElement {}
class CoreItem:CoreElement {}

class CoreA<aType:CoreElement> { }
class CoreB:CoreA<CoreItem> { }

class CoreSomeClass<T:CoreElement> {
func foo() -> CoreA<T> {
return CoreA<T>()
}
}
class CoreOtherClass:CoreSomeClass<CoreItem> {
override func foo() -> CoreA<CoreItem> {
return CoreB()
}
}

关于swift - 在通用元类型函数中返回具有特定元类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37432535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com