【问题标题】:Swift protocol with associatedtype as a parameter type将关联类型作为参数类型的 Swift 协议
【发布时间】:2017-12-26 12:36:39
【问题描述】:

所以我这里有这个协议

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

那么,我可以从我的代码中更改一些东西以使这种情况有效吗?提前致谢。

【问题讨论】:

    标签: ios swift swift-protocols associated-types


    【解决方案1】:

    您不能将具有关联类型的协议用作字段。

    您只能将它们用作类的实现。在大多数情况下,这些类应该是通用的。

    例如,允许使用以下代码:

    public struct CreateNewAccount<T, K>: UseCase {
    
        public typealias ResponseType = T
    
        public typealias Parameters = K
    }
    

    等等,

    private let createNewAccount: CreateNewAccount&lt;YouClass1,YouClass2&gt;

    或通过其他协议以某种方式包装它。

    【讨论】:

    • 您好,感谢您的回答。所以这意味着我必须直接在其消费者上使用CreateNewAccount?你有其他想法来反驳这个案子吗?所以我可以将抽象(协议)类型传递给消费者,而不是具体实现。
    • 据我所知,如果您只想使用协议,唯一的解决方案是使用其他协议。 public struct CreateNewAccount&lt;T, K&gt;: UseCase, YourNewSimpleProtocol
    猜你喜欢
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多