One of the coolest things about Swift is working with closures. Closures aren’t specific to Swift, you get them in lots of other languages, but they’re on steroids when you use them with Swift!


1
let impersonalClosure: (String) -> () = { (IDeserveANameYouKnow: String) in print(IDeserveANameYouKnow) }

Basically a closure is an anonymous function you can pass around anywhere, call anywhere and return anywhere. Now that I think about it they sound so impersonal! Poor closures. Anyway, one of the great things about levelling up my Functional Swift skills is that I’ve been using a lot of closures and getting much more comfortable with them. One of the more interesting things that happened recently though was the discovery of @autoclosure.

Here is a super quick example of one:


1
2
func tryAutoClosures(_ expression: @autoclosure () -> Bool) {
}

Now the idea with autoclosures is that they are called lazily (when they are required) and they save you having to pre-form an expression to pass in and you can literally ‘plonk’ in your values/code right there in the argument.


1
tryAutoClosures(3 > 2)

This saves you from having to use the curly braces which would usually be required to pass in a closure:


1
tryAutoClosures({3 > 2})

Now the above idea is a bit contrived, but what if you wanted to do something automatically and save more code?


1
2
3
4
5
6
7
func updateUI(_ update: @escaping () > Void) {

// animate stuff

// refreshUI with(update)

}

Something like this could be a real timesaver.

Just another cool feature in Swift that I’m getting used to!