【发布时间】: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