Closures
In Swift, a closure is a type of anonymous function that can be stored as a value and passed as an argument. Or as Apple phrases it:
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. (Apple)
When a method or function takes a closure as one of its arguments the closure is passed inside a pair of code braces.
func num(n: () -> Int) -> Int {
return n()*2
}
var a = 10
var b = 15
num ({() in a*b}) // returns 300
The above example shows a closure written out in full and passed to the num() function, but normally we'd abbreviate one as simple as this to:
num ({a*b}) // returns 300
Autoclosures
Put simply, an autoclosure enables you to omit the braces, but you can only use an autoclosure if the function or method isn't passed any arguments.
func num(n: @autoclosure() -> Int) -> Int {
return n()*2
}
var a = 10
var b = 15
num (a*b) // returns 300
You activate the autoclosure functionality by placing the
@autoclosure attribute after the closure's parameter name and in front of the closure requirements. Now the closure not only doesn't require the braces, or indeed the
() in a*b syntax, but rejects them. We must therefore abbreviate to only include the calculation of the return value and nothing more.
Further use
If we were to pass a function call as an autoclosure argument, then it would similarly omit code the braces:
func num(n: @autoclosure() -> Int) -> Int {
return n()
}
func go(x:Int, y:Int) -> Int {
return x*y/x + x*y/y
}
num (go(10,12)) // returns 22
Of course not being able to pass arguments to an autoclosure does place restrictions on its use, but hopefully this post helps to demystify its purpose.
Comments
Post a Comment