简体   繁体   English

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

[英]How to create a protocol with a generic function extending type

I'm trying to do a protocol with a generic function where T is not just equal to the type, but extends it. 我正在尝试使用泛型函数来执行协议,其中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()
    }
}

But I get this error 但是我得到了这个错误

Type 'ClassA' does not conform to protocol 'MyProtocol' 类型'ClassA'不符合协议'MyProtocol'

because Item1 is not equal to MainItem (it expands it). 因为Item1不等于MainItem (它扩展了它)。 How can you make it work? 你怎么能让它发挥作用?

For example, in Java everything can be done using abstract class: 例如,在Java中,一切都可以使用抽象类来完成:

abstract class MyProtocol {
    abstract <T extends MainItem> T myFunc()
}

Generics is not the way to go for your requirements. 泛型不是满足您要求的方式。 When you declare a generic function in a protocol, the generic type parameter will mean that the same function works for all types that satisfy the generic type restriction, but the function signature still needs to be intact for all conforming types. 在协议中声明泛型函数时,泛型类型参数将表示相同的函数适用于满足泛型类型限制的所有类型,但函数签名仍需要对所有符合类型的函数完整。

What you are looking for is a protocol with associated type . 您正在寻找的是具有相关类型协议 An associated type on a protocol means that the conforming type can decide what concrete type to use in place of the associated type, hence allowing you to use different associated types in different conforming classes. 协议上的关联类型意味着符合类型可以决定使用哪种具体类型来代替关联类型,因此允许您在不同的符合类中使用不同的关联类型。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM