[英]Swift protocol with associatedtype as a parameter type
所以这里我有这个协议
public protocol UseCase {
associatedtype ResponseType
associatedtype Parameters
func build(params: Parameters) -> Single<ResponseType>
}
public extension UseCase {
func execute(params: Parameters) -> Single<ResponseType> {
return build(params: params)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: DispatchQoS.background))
.observeOn(MainScheduler.instance)
}
}
我有一个像这样实现用UseCase
协议的结构
public struct CreateNewAccount: UseCase {
private let repository: AuthRepository
public init(repository: AuthRepository) {
self.repository = repository
}
public func build(params: Params) -> Single<User> {
return repository.register(params: params)
}
public struct Params: RequestParams {
...
}
}
我想在另一个类上使用这个CreateNewAccount
,但我不想直接使用CreateNewAccount
,我想将它作为一个UseCase
传递,因为它是一个协议,它可以很容易地被模拟以进行测试。 但是当我做这样的事情时
class RegisterViewModel: ViewModel {
private let createNewAccount: UseCase // Error on this line
init(createNewAccount: UseCase) { // Error on this line
self.createNewAccount = createNewAccount
}
}
这给了我这样的错误
Error:(34, 35) protocol 'UseCase' can only be used as a generic constraint because it has Self or associated type requirements
那么,是否可以从我的代码中更改某些内容以使这种情况有效? 提前致谢。
您不能使用具有关联类型的协议作为字段。
您必须仅将它们用作类的实现。 在大多数情况下,这些类应该是通用的。
例如,允许使用以下代码:
public struct CreateNewAccount<T, K>: UseCase {
public typealias ResponseType = T
public typealias Parameters = K
}
所以,
private let createNewAccount: CreateNewAccount<YouClass1,YouClass2>
或者通过其他协议以某种方式包装它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.