Skip to content

Instantly share code, notes, and snippets.

@thanhluu
Created May 19, 2016 16:38
Show Gist options
  • Save thanhluu/49423a1d66b9625ed7d913fb88304799 to your computer and use it in GitHub Desktop.
Save thanhluu/49423a1d66b9625ed7d913fb88304799 to your computer and use it in GitHub Desktop.
Closure Expressions
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