Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift closure - Shorthand Closure
// Declare a variable to hold a closure
var add: (Int, Int) -> Int
/** SHORTHAND SYNTAX **/
// Not need return keyword when only have single return statement
add = {(a: Int, b: Int) -> Int in
a + b
}
add(1, 1)
// Remove return type and parameters type
// Because we already declare: var add: (Int, Int) -> Int
add = {(a, b) in
a + b
}
add(9, 2)
// Remove parameters, Swift will refer parameters by number, start from 0:
add = {
$0 + $1
}
add(99, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment