I've been trying to implement an undo stack that leverages the type system in Swift. My particular approach is to memoize both the function used and the parameters passed to that function. If I can get this to work, as I see it, it would be an improvement over the pattern described in GOF. No success yet.
public struct Command <Parameters, Results> {
let action : (Parameters -> Results)
let parameters : Parameters
init(action a : Parameters -> Results, parameters p : Parameters) { action = a
parameters = p
}}
let cmd1 = Command(action: { return $0 + " World" }, parameters: ("Hello"))
let cmd2 = Command(action: { return $0 + $1 + $2 }, parameters: (1, 2, 3))
let undos = [cmd1, cmd2]
Error:
'_' is not convertible to 'Command<(Int, Int, Int), Int>'
Type of expression is ambiguous without more context
I get that the generic types are not equivalent for all instances of Command, but I'm not sure what the fix for this would be given the new semantics.
I'm not going to define equality for every type of tuple that wants to participate in the undo system (this is more annoying than GOF).
So in an attempt to get the array to accept heterogeneous types, I tried pulling the generic types into a protocol as type aliases. Problem again: this only shifts the problem around, since it's the Command that now needs nail down the type of the alias, which forces a different Command implementation for each pair of associated types.
At this point I've run out of ideas. What am I missing?
Thanks,
—Jake