Created
November 13, 2017 12:54
-
-
Save fitomad/2be4dbcec63a952fc85cbfd47874c2e2 to your computer and use it in GitHub Desktop.
Example about @autoclosure in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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