Skip to content

Instantly share code, notes, and snippets.

@algal
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algal/8f944f35fab43ecf7b5e to your computer and use it in GitHub Desktop.
Save algal/8f944f35fab43ecf7b5e to your computer and use it in GitHub Desktop.
Enum in a Struct vs Enum with Associated Values
/*
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
}
}
@algal
Copy link
Author

algal commented Feb 9, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment