I have one framework ProviderFramework with the following contents:
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:
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. 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:
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:
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'
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? Since you confirmed typealias T
as ProviderFramework.Model
in the extension of class Provider
.
class Consumer {
var provider: Provider?
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.