Skip to content

Instantly share code, notes, and snippets.

@ansonj ansonj/repeater.swift
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.