There are few structs which conform to common protocol:
protocol StateMachineState {...}
struct VideoMode: StateMachineState {
func transit(state: PhotoMode) -> Transition? {
return Transition(targetState: state)
}
}
struct PhotoMode: StateMachineState {
func transit(state: VideoMode) -> Transition? {
return Transition(targetState: state)
}
}
and the usage of the member method of such:
func transit(target_state: PhotoMode) {
process(transition: state.transit(state: target_state))
}
func transit(target_state: VideoMode) {
process(transition: state.transit(state: target_state))
}
Notice, there is the same implementation in all func transit()
, they differ only in parameter type. Both VideoMode
and PhotoMode
conform to the same protocol. The goal is to reduce code repetition and try to apply Generics? to write one common function accepting all the types conform to common protocol. I assume the state.transit(...)
call requires the concrete type – either VideoMode
or PhotoMode
to be identified somehow… something like:
func transit<Mode: StateMachineState>(target_state: Mode) { // Mode equals StateMachineState
try process(transition: state.transit(state: target_state)) // Requires VideMode or PhotoMode
}
The code reports “Not exact matches in call to instance method transit” and offers the candidates using VideoMode
and PhotoMode
respectively.
Is there a way to use the generics to let the compiler generate the repetitive methods on its own or I have to write and repeat all over by myself (The body is always the same)?
(I am coming from C++ world where it is pretty common technique but in Swift I struggle to make it compiled and run…)