我有一个类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/