Alexito's World

A world of coding 💻, by Alejandro Martinez

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 liked this article please consider supporting me