22 July 2014 1min read

The power of clousures in Swift

I really like when a language gives the power to extend it easily. In Swift the clousures are really powerful.

You can use clousures to do lazyness and implement the while loop:

func myWhile (cond : @auto_closure () -> Bool, body : () -> ()) { if (cond()) { body() ; myWhile(cond, body) } }

var y : Int = 3

myWhile (y > 0) { 
    print (y) y = y - 1 
}

Or implement assert without macros:

func assert(predicate : @auto_closure () -> Bool) {
    #if !NDEBUG
        if !predicate() {
            abort()
        }
    #endif
}

assert(someExpensiveComputation() != 42)

But remember, with great power comes great responsibility.

If you enjoyed this post

Continue reading