如何使用SWIFT协议与泛型方法和泛型类型
问题描述:
我有一个类StateMachine<A>
如何使用SWIFT协议与泛型方法和泛型类型
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
}
}
+0
Excellant答案!谢谢。 –
代码有很多问题,现在:你不能把嵌套类型泛型('枚举State');你必须初始化'init'中的所有非可选属性;你必须在委托协议中指定'associatedtype'。 – user28434