如何将 Swift 协议与通用方法和通用类型一起使用

How to use Swift Protocols with Generic methods and Generic Types

我有一个classStateMachine<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
    }
}

和委托协议StateMachineDelegate

protocol StateMachineDelegate {
    func updateWith(content: A)
}  

我想表达的是,如果 StateMachine 是使用 A 类型创建的,则委托应实现方法 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)
}

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

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
    }
}