【问题标题】:Issue with Protocols with Associated Types in SwiftSwift 中具有关联类型的协议问题
【发布时间】:2017-06-02 23:20:48
【问题描述】:

我有一个框架ProviderFramework,内容如下:

public class Provider {

    public func fun(some: Model) {

    }

}

public class Model {

    public let id: Int

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

}

还有另一个UserFramework,内容如下:

public protocol ProviderProtocol {

    func fun(some: ModelProtocol)

}

public protocol ModelProtocol {

    var id: Int {get}

}

我想要的是使 Provider 类符合 ProviderProtocol 类。所以在一个导入前面提到的两个框架的框架中,我有这个:

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

很遗憾,这会导致第二个一致性错误。 所以,我尝试使用关联类型,我的 ProviderProtocol 变成了这样:

public protocol ProviderProtocol {

    associatedtype T: ModelProtocol

    func fun(some: T)

}

以及有问题的一致性:

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

现在没有任何编译错误,但是如果我想将协议用作这样的类型:

class Consumer {

    var provider: ProviderProtocol?

}

我再次收到错误消息:'Protocol 'ProviderProtocol' 只能用作通用约束,因为它具有 Self 或关联的类型要求'

我希望能够做最后一件事。我的代码中是否有一些错误,或者如果没有,是否有针对此问题的替代解决方案?

非常感谢。

【问题讨论】:

    标签: ios swift swift3 protocols swift-protocols


    【解决方案1】:

    按照第二种方式,为什么不用Provider而不是ProviderProtocol呢?由于您在类Provider 的扩展中确认typealias TProviderFramework.Model

    class Consumer {
        var provider: Provider?
    }
    

    【讨论】:

    • This: extension Provider: ProviderProtocol { public func fun(some: ModelProtocol) { } } 向 Provider 类添加了另一个函数,这不是我的意思。我想获取 public func fun(some: Model) 函数以某种方式使 Provider 类符合 ProviderProtocol 以便在调用 fun 函数时调用原始方法。
    • 为什么不直接更改类Provider?听起来 Provider 类被锁定了,不能更改吗?所以你想使用扩展来覆盖原来的行为?
    • 如果我更改 Provider 类以符合 ProviderProtocol,我将不得不在 ProviderFramework 中导入 UserFramework,这会在它们之间创建我不想要的依赖关系。我想在导入它们的框架之外的第三类中解决依赖关系。
    • Consumer 类是 UserFramework 的一部分,因此直接使用 Provider 类需要在 UserFramework 中导入我不想要的 ProviderFramework。我希望 UserFramework 和 ProviderFramework 相互独立,并有另一个导入它们的类来连接它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    相关资源
    最近更新 更多