Created
May 19, 2016 16:38
-
-
Save thanhluu/49423a1d66b9625ed7d913fb88304799 to your computer and use it in GitHub Desktop.
Closure Expressions
This file contains hidden or 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
func doubler(i: Int) -> Int { | |
return i * 2 | |
} | |
let doubleFunction = doubler | |
doubleFunction(2) | |
let numbers = [1,2,3,4,5] | |
let doubleNumbers = numbers.map(doubleFunction) | |
/***************/ | |
let tripledNumbers = numbers.map({ (i: Int) -> Int in return i * 3 }) | |
// Rule #2: Inferring Type From Context | |
numbers.map({ i in return i * 3 }) | |
// Rule #3: Implicit Returns from Single-Expression Closures | |
numbers.map({ i in i * 3 }) | |
// Rule #4: Shorthand Argument Names | |
numbers.map({ $0 * 3 }) | |
// Rule #5: Trailing Closures | |
numbers.map() { $0 * 3 } | |
/***************/ | |
[1,2,3,4,5].map() { | |
(digit: Int) -> Int in | |
if digit % 2 == 0 { | |
return digit / 2 | |
} else { | |
return digit | |
} | |
} | |
/***************/ | |
// Rule #6: Ignoring Parentheses | |
numbers.map { $0 * 3 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment