Skip to content

Instantly share code, notes, and snippets.

@ansonj
Last active August 29, 2015 14:17
Show Gist options
  • Save ansonj/3c6105b4c36067d8a50e to your computer and use it in GitHub Desktop.
Save ansonj/3c6105b4c36067d8a50e to your computer and use it in GitHub Desktop.
Repeater function in Swift
// 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