Skip to content

Instantly share code, notes, and snippets.

@curtclifton
Last active August 29, 2015 14:02
Show Gist options
  • Save curtclifton/9923c50bfc4b0e0920e2 to your computer and use it in GitHub Desktop.
Save curtclifton/9923c50bfc4b0e0920e2 to your computer and use it in GitHub Desktop.
Information hiding in Swift by nesting class declaration inside a function
protocol Counter {
var value: Int { get }
func moveTowardZero()
}
func makeCounterStartingAt(value: Int) -> Counter {
// Since this class declaration is nested in the generator function, the returned value is only accessible via the Counter protocol
class CountImplementation: Counter {
var value: Int
init(value: Int) {
self.value = value
}
func countDown() {
value -= 1
}
func countUp() {
value += 1
}
func moveTowardZero() {
switch value {
case 0:
return
case let x where x < 0:
countUp()
default:
countDown()
}
}
}
return CountImplementation(value: value)
}
func demonstrateCounter(counter: Counter) {
println(counter.value)
while counter.value != 0 {
counter.moveTowardZero()
println(counter.value)
}
}
let counter1 = makeCounterStartingAt(3)
demonstrateCounter(counter1)
/* prints:
3
2
1
0
*/
let counter2 = makeCounterStartingAt(-4)
demonstrateCounter(counter2)
/* prints:
-4
-3
-2
-1
0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment