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}

Next step: backend.

Parse will be close down pretty soon so I have to look for the alternative database server. Debating bw backendless.com and AWS. My goal this coming week is to test both of them out, if lucky.

closures and delegates

Spend a whole day reading closures and delegates.
I learned a lot but am still confused. Phew~


func differenceBetweenNumbers(a: Int, b:Int) -> (Int) {
  return a - b
}

// The type of “differenceBetweenNumbers" is (Int, Int) - > Int.

/*
 Now that we have a TYPE, we want to create a function that takes in
 this TYPE of function as an argument in its parameter. 
*/
func mathOperation(anyAddFunc: (Int, Int) -> Int, a: Int, b: Int) -> Int{
    return anyAddFunc(a,b)
}
// Calling the function

var someVariable = mathOperation(differenceBetweenNumbers, a: 10, b: 5)

// This will give you the result of 5


}