Friday, April 8, 2016

Closure Expressions and Closure Shorthand Syntax

Today, finally I figured it out what is $0 stands for. 
Thanks to treehouse, and Pasan Premaratne is a great instructor 

https://teamtreehouse.com/library/swift-closures/closures-and-closure-expressions/closure-expression-syntax




//: Closure Expressions

func doubler(i: Int) -> Int {
    return i * 2
}

let doubleFunction = doubler
doubleFunction(4)

let numbers = [1,2,3,4,5]
let doubledNumbers = numbers.map(doubleFunction)

// Using closure expressions with the map function
let tripledNumbers = numbers.map({(i: Int) -> Int in return i * 3 })

// Using closure expressions with the sorted function
var names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

// Function to sort strings in ascending order
func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}

//sorted(names, backwards)

//let sortedNames = sorted(names, {(s1: String, s2: String) -> Bool in return s1 > s2 })

//////////////////////////////
// Closure Shorthand Syntax //
//////////////////////////////

// Rule #1
[1,2,3,4,5].map({ (i: Int) -> Int in return i * 3 })

// Rule #2: Infering Type from Context
[1,2,3,4,5].map({i in return i * 3})

// Rule #3: Implicit Return from Single Expression Closures
[1,2,3,4,5].map({i in i * 3})

// Rule #4: Shorthand Argument Names
[1,2,3,4,5].map({$0 * 3})

// Rule #5: Trailing Closures
[1,2,3,4,5].map() {$0 * 3}

// Rule #6: Ignoring Parentheses

[1,2,3,4,5].map {$0 * 3}

No comments:

Post a Comment