swift - 如何将 Swift 协议(protocol)与泛型方法和泛型类型一起使用

标签 swift generics swift-protocols

我有一个类StateMachine<A>

final class StateMachine<A> {

    private var previousState: State? = nil
    private var currentState: State
    private var content: A?
    var delegate: StateMachineDelegate?
    var state: State = .loading {
        didSet {
            previousState = currentState
            currentState = state
        }
    }

    init(currentState: State, delegate: StateMachineDelegate?) {
        self.currentState = currentState
    }
}

和委托(delegate)协议(protocol)StateMachineDelegate

protocol StateMachineDelegate {
    func updateWith(content: A)
}  

我想表达的是,如果 StateMachine 是用 A 类型创建的,委托(delegate)应该实现方法 func updateWith(content: A)它接受相同类型 A 的参数。这可能吗?

最佳答案

您可以通过添加另一个类型参数来实现您的要求:

final class StateMachine<A, Delegate: StateMachineDelegate> where Delegate.A == A {

    private var previousState: State? = nil
    private var currentState: State
    private var content: A?
    var delegate: Delegate?
    var state: State = .loading {
        didSet {
            previousState = currentState
            currentState = state
            delegate?.updateWith(content: state)
        }
    }

    init(currentState: State, delegate: Delegate?) {
        self.currentState = currentState
    }
}

protocol StateMachineDelegate {
    associatedtype A
    func updateWith(content: A)
}

但我不会这样做。如果您的委托(delegate)真的只是一个更新方法,那么闭包是更好的解决方案:

final class StateMachine<A> {    
    // ...
    private var content: A?
    var notify: (A) -> Void

    var state: State = .loading {
        didSet {
            previousState = currentState
            currentState = state
            notify(state)
        }
    }

    init(currentState: State, notify: @escaping (A) -> Void) {
        self.currentState = currentState
        self.notify = notify
    }
}

关于swift - 如何将 Swift 协议(protocol)与泛型方法和泛型类型一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020126/

相关文章:

swift - 适用于 iOS 的 Spring RestTemplate (Swift 4)

ios - SKNode 现在显示在另一个类中

ios - Swift - 完成在动画结束之前结束

java - 为什么这会将类型解析为接口(interface)?

swift - 是否可以为协议(protocol)创建仅类扩展?

swift - 如何制作一个声明协议(protocol)类型属性的协议(protocol)?

ios - Swift - NSURL 错误

c# - 获取属于特定开放泛型类型的类的所有属性

c# - 调用泛型方法

ios - 具有原始值的枚举,可编码