I am writing a library for state management. It's basically a simplified observer pattern, with just 1 single observer/listener.
Right now I have this and it worked well:
public final class StateStore<S> {
private var currentState: S
public var listener: ((S) -> Void)? = nil
public init(initialState: S) {
currentState = initialState
}
func update(_ block: (inout S) -> Void) {
var nextState = currentState // struct's copy on write
block(&nextState)
currentState = nextState
listener?(currentState)
}
}
However, I would like to change it to protocol instead of block. Something like:
public protocol StateListener: AnyObject {
associatedtype S
func didUpdateState(_ state: S)
}
public final class StateStore<S> {
...
public weak var listener: StateListener<S>? // <- how to deal with associate type
...
}
I am not able to do so because in the above S
is associate type, not generic type. So I got error saying Cannot specialize non-generic type 'StateListener'
I have looked at this but not helpful: Using generic protocols in generic classes