Last active
August 29, 2015 14:17
-
-
Save ansonj/3c6105b4c36067d8a50e to your computer and use it in GitHub Desktop.
Repeater function in Swift
This file contains 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
// Runs in a Playground | |
func repeat(function: () -> (), untilNoChangeTo sentinel: () -> String) { | |
var initial, final: String | |
do { | |
initial = sentinel() | |
function() | |
final = sentinel() | |
} while initial != final | |
} | |
func repeatGenerically<T: Equatable>(function: () -> (), untilNoChangeTo sentinel: () -> T) { | |
var initial, final: T | |
do { | |
initial = sentinel() | |
function() | |
final = sentinel() | |
} while initial != final | |
} | |
class Repeater { | |
var count = 0 | |
let target: Int | |
init(count: Int, target: Int) { | |
self.count = count | |
self.target = target | |
} | |
func increment() { | |
if count < target { | |
++count | |
} | |
} | |
func countAsString() -> String { | |
return "\(count)" | |
} | |
func countAsDouble() -> Double { | |
return Double(count) | |
} | |
} | |
let rep1 = Repeater(count: 0, target: 5) | |
let rep2 = Repeater(count: 0, target: 5) | |
repeat(rep1.increment, untilNoChangeTo: rep1.countAsString) | |
repeatGenerically(rep2.increment, untilNoChangeTo: rep2.countAsDouble) | |
println(rep1.count) | |
println(rep2.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment