Skip to content

Instantly share code, notes, and snippets.

@jonjesbuzz
Last active March 25, 2017 16:38
Show Gist options
  • Save jonjesbuzz/22c56b5927e58b3f9ac66b6f4e2cff88 to your computer and use it in GitHub Desktop.
Save jonjesbuzz/22c56b5927e58b3f9ac66b6f4e2cff88 to your computer and use it in GitHub Desktop.
/**
A for-loop using functions to evaluate and express the conditions and statements.
- parameters:
- initialize: A function that initializes a variable or tuple.
- condition: The loop condition evaluated after each loop.
- increment: The increment statement to move the loop closer to completion
- body: The loop body.
*/
func loop<T>(initialize: () -> (T), condition: (T)->(Bool), increment: (T)->(T), body: (T)->()) {
var data = initialize()
while(condition(data)) {
body(data)
data = increment(data)
}
}
// Example call with one variable.
loop(initialize: { 0 }, condition: { $0 < 10 }, increment: { $0 + 1 }) {
print($0)
}
// Example call with two variables.
loop(initialize: { (0, 0) }, condition: { $0.0 < 10 }, increment: { ($0.0 + 1, $0.1 + 2) }) {
print("\($0.0)\t\($0.1)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment