Last active
November 6, 2018 07:41
-
-
Save nhathm/dcce9bacdc16eaf4e957f23b9d287ed7 to your computer and use it in GitHub Desktop.
Swift closure - Shorthand Closure
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
// 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