Skip to content

Instantly share code, notes, and snippets.

@fitomad
Created November 13, 2017 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/2be4dbcec63a952fc85cbfd47874c2e2 to your computer and use it in GitHub Desktop.
Save fitomad/2be4dbcec63a952fc85cbfd47874c2e2 to your computer and use it in GitHub Desktop.
Example about @autoclosure in Swift
/*
An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function.
It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it
*/
let greeting: () -> (String) = {
print("You can do other things here...")
return "Hi everyone!"
}
/// With autoclosure feature...
func autoclosureFunction(message: @autoclosure () -> (String)) -> Void
{
print(message())
}
/// Without autoclosure
func nonAutoclosureFunction(message: () -> (String)) -> Void
{
print(message())
}
// Autoclosure calling...
autoclosureFunction(message: greeting())
// OK. @autoclosure create a wrap around parameter
autoclosureFunction(message: "Hi everyone from a common parameter.")
// Non autoclosure calling...
nonAutoclosureFunction(message: { return "Hi everyone without a wrap !" })
// Line below terminate with ERROR
nonAutoclosureFunction(message: "Hi everyone without a wrap and from a common parameter!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment