Alejandro Martinez

BlogPodcastPortfolio Youtube

22 July, 2014Development🕐 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 have any feedback you can reach me at alexito4

On Core Data, JSON, libraries...Swift continues changing

Alejandro Martinez
alexito4@gmail.com

Buka pintu

alexito4
alexito4