Last active
August 29, 2015 14:15
-
-
Save algal/8f944f35fab43ecf7b5e to your computer and use it in GitHub Desktop.
Enum in a Struct vs Enum with Associated Values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The examples below show two ways to model a state machine with two states, | |
On and Off, with an additional constant Int property. | |
On -> Off and Off -> On transitions must be inititated by calling flip() | |
*/ | |
// struct containing a property and an enum | |
func ==(lhs:Foo,rhs:Foo) -> Bool { | |
switch (lhs.state,rhs.state) { | |
case (.On,.On): return lhs.node==rhs.node | |
case (.Off,.Off): return lhs.node==rhs.node | |
default: return false | |
} | |
} | |
struct Foo : Equatable { | |
let node:Int | |
var state:FooState | |
enum FooState { | |
case On | |
case Off | |
} | |
mutating func flip() -> () { | |
self.state = (self.state == .On) ? .Off : .On | |
} | |
} | |
// enum containing associated values | |
func ==(lhs:Bar,rhs:Bar) -> Bool { | |
switch (lhs,rhs) { | |
case (.On(let l),.On(let r)): return l==r | |
case (.Off(let l),.Off(let r)): return l==r | |
default: return false | |
} | |
} | |
enum Bar { | |
case On(node:Int) | |
case Off(node:Int) | |
mutating func flip() -> () { | |
switch self { | |
case .On(let n): self = .Off(n) | |
case .Off(let n): self = .On(n) | |
} | |
} | |
} | |
// addendum: using an enclosing reference type FooClass instead of a value type: | |
class FooClass { | |
init(node:Int,state:FooState) { | |
self.node = node | |
self.state = state | |
} | |
let node:Int | |
var state:FooState | |
enum FooState { | |
case On | |
case Off | |
} | |
func flip() -> () { | |
self.state = (self.state == .On) ? .Off : .On | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By the way, @jemmons, I'm aware these examples are not quite parallel to the design you've been developing.
I just wanted to illustrate how enums with associated values are not so different from types that contain enums plus something else. So that associated value could be a reference type, even a reference to an instance that represents the state machine.