如何使用泛型函数扩展类型创建协议

问题描述 投票:3回答:1

我正在尝试使用泛型函数来执行协议,其中T不仅仅等于类型,而是扩展它。

class MainItem {}
class Item1: MainItem {}
class Item2: MainItem {}

protocol MyProtocol {
    func myFunc<T: MainItem>() -> T // T extends MainItem
}

class ClassA: MyProtocol {
    func myFunc() -> Item1 { // not MainItem
        return Item1()
    }
}

class ClassB: MyProtocol {
    func myFunc() -> Item2 { // not MainItem
        return Item2()
    }
}

但是我得到了这个错误

类型'ClassA'不符合协议'MyProtocol'

因为Item1不等于MainItem(它扩展了它)。你怎么能让它发挥作用?

例如,在Java中,一切都可以使用抽象类来完成:

abstract class MyProtocol {
    abstract <T extends MainItem> T myFunc()
}
swift generics protocols swift-protocols
1个回答
4
投票

泛型不是满足您要求的方式。在协议中声明泛型函数时,泛型类型参数将表示相同的函数适用于满足泛型类型限制的所有类型,但函数签名仍需要对所有符合类型的函数完整。

你在寻找什么是protocol with associated type。协议上的关联类型意味着符合类型可以决定使用哪种具体类型来代替关联类型,因此允许您在不同的符合类中使用不同的关联类型。

protocol MyProtocol {
    associatedtype MyType: MainItem
    func myFunc() -> MyType
}

class ClassA: MyProtocol {
    func myFunc() -> Item1 {
        return Item1()
    }
}

class ClassB: MyProtocol {
    func myFunc() -> Item2 {
        return Item2()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.