简体   繁体   English

Swift中具有关联类型的协议的问题

[英]Issue with Protocols with Associated Types in Swift

I have one framework ProviderFramework with the following contents: 我有一个具有以下内容的框架ProviderFramework:

public class Provider {

    public func fun(some: Model) {

    }

}

public class Model {

    public let id: Int

    init(id: Int) {
        self.id = id
    }

}

and another UserFramework with the following contents: 和另一个具有以下内容的UserFramework:

public protocol ProviderProtocol {

    func fun(some: ModelProtocol)

}

public protocol ModelProtocol {

    var id: Int {get}

}

What I want is to make the Provider class conform to the ProviderProtocol class. 我想要的是使Provider类与ProviderProtocol类保持一致。 So in a framework that imports both of the previously mentioned frameworks I have this: 因此,在导入了前面提到的两个框架的框架中,我都有以下内容:

extension ProviderFramework.Model: UserFramework.ModelProtocol {}
extension ProviderFramework.Provider: UserFramework.ProviderProtocol {}

Unfortunately, this results in an error for the second conformance. 不幸的是,这导致第二一致性的错误。 So, I tried using an associated types and my ProviderProtocol turned into this: 因此,我尝试使用关联的类型,而我的ProviderProtocol变成了这样:

public protocol ProviderProtocol {

    associatedtype T: ModelProtocol

    func fun(some: T)

}

and the problematic conformance to this: 以及与此相关的问题:

extension ProviderFramework.Provider: UserFramework.ProviderProtocol {
    public typealias T = ProviderFramework.Model
}

Now there aren't any compile errors, but if I want to use the Protocol as a type like this: 现在没有任何编译错误,但是如果我想使用Protocol这样的类型:

class Consumer {

    var provider: ProviderProtocol?

}

I again get an error: 'Protocol 'ProviderProtocol' can only be used as a generic constraint because it has Self or associated type requirements' 我再次收到错误消息:“协议'ProviderProtocol'只能用作通用约束,因为它具有Self或关联的类型要求”

I would want to be able to do the last thing. 我希望能够做最后一件事。 Do I have some bug in my code or if not is there some alternative solution for this problem? 我的代码中是否存在一些错误,或者如果没有,该问题是否有其他解决方案?

Thanks a lot in advance. 非常感谢。

According to the second approach, why not use Provider instead of ProviderProtocol? 根据第二种方法,为什么不使用Provider而不是ProviderProtocol? Since you confirmed typealias T as ProviderFramework.Model in the extension of class Provider . 由于您确认typealias TProviderFramework.Model类的扩展Provider

class Consumer {
    var provider: Provider?
}

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

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