Monday, July 14, 2014

Closures

Simple Closure

var myClosure = {
    () -> Void in
    println("My Closure")
}


myClosure()

//Console output:
My Closure


Closure with parameters

var myClosure2Times = {
    (myNum: Int) -> Int in
    return myNum * 2
}

println("2 * 10 = \(myClosure2Times(10))")

//Console output:
2 * 10 = 20

Friday, July 4, 2014

functions

Function Format

func functionName(parameterName: Type...) -> returnType {

}

func favoriteNumber(person: String, number: Int) -> String {
    let returnString = person + " likes number " + String(number) + "."
    return returnString
}


println(favoriteNumber("Jeremy", 7))

//Console output: Jeremy likes number 7.

//The above function may be shorten by removing "returnString" as below:

func favoriteNumber(person: String, number: Int) -> String {
    return person + " likes number " + String(number) + "."
}

Ignored return value
//if the function is called as below (the above println is now removed):

favoriteNumber("Jeremy", 7)

//The playground prints the return value of "Jeremy likes number 7."
//However, the return value is not used and hence is ignored.

Function without parameters and return values

//Empty () and no ->

func sayHello() {
    println("Hello!!")
}

sayHello()

//Console output: Hello!!

Function with multiple return values

//Use ( ) to include multiple return types

func multipleReturnValues () -> (the1st: String, the2nd: String, the3rd: String) {
    return ("M", "I", "T")
}
let result = multipleReturnValues()
println("\(result.the1st)\(result.the2nd)\(result.the3rd)")

//Console output: MIT

Function with external parameter names

//External parameter names are used to clearly show the parameter name while calling a functions.


func extParaNameFunc(ext1 para1: Int, ext2 para2: Int) {
    println("ext1 = \(para1), ext2 = \(para2)")
}

extParaNameFunc(ext1: 3, ext2: 5)

//Console output: ext1 = 3, ext2 = 5

Shorthand external parameter names

//Simply put a # sign before the parameter name.
//Then a sharing external and internal parameter name is used.

func extParaNameFunc2(#para1: Int, #para2: Int) {
    println("para1 = \(para1), para2 = \(para2)")
}
extParaNameFunc2(para1: 4, para2: 6)

//Console output: para1 = 4, para2 = 6

Function with a default value

func extParaNameFunc3(input1: Int, input2: Int, input3: String = "default") {
    println("\(input1) \(input2) \(input3)")
}

extParaNameFunc3(1, 2)

extParaNameFunc3(1, 2, input3: "yes")

//Input3 is the automatic external name
//Console output: 
1 2 default
1 2 yes

Variadic parameters (zero to multiple input values)
//Use ...


func sumParameters(numbers: Int...) {
    var mySum = 0;
    for number in numbers {
        mySum += number
    }
    println("Sum is \(mySum).")
}
sumParameters(1, 2, 3, 4)

sumParameters(10, 20, 30)

//Console output: 
Sum is 10.
Sum is 60.

Variable parameters
Parameters by default are constant parameter and hence can not be changed.
To declare variable parameters, use var.


func alignCenter(var myString: String, number: Int) {
    for _ in 1...number {
        myString = "-" + myString + "-"
    }
    println("\(myString)")
}

alignCenter("Hi",5)

//Console output: 
-----Hi-----

In-out Parameters
//Use inout

func multiplyBy2(inout var1: Int, inout var2: Int) {
    var1 *= 2
    var2 *= 2
}

var i = 3
var j = 5
multiplyBy2(&i, &j) //Use & sign

println("i = \(i), j = \(j)")

//Console output: 
i = 6, j = 10

Function types



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

var calculation: (Int, Int) -> Int = addInts 
//(IntInt) -> Int is the function type


println("Result: \(calculation(1, 3))")

//Console output: 
Result: 4

Wednesday, July 2, 2014

for / while loops


for loops

The for-in loop iterate over ranges of numbers, characters in a string, items in an array or a dictionary.

ranges of numbers
for count in 1...4 {
    println("count = \(count)")

}


//Console output:
count = 1
count = 2
count = 3
count = 4

var sum = 0
for count in 1...4 {
    sum += count
    println("sum = \(sum)")
}

//Console output:
sum = 1
sum = 3
sum = 6
sum = 10

Characters in a string

for myChar in "ABCDE" {
    println("\(myChar)")
}

//Console output:
A
B
C
D
E
for var count = 1; count < 5; count++ {
    println("count = \(count)")
}
//No ( )
//Console output:
count = 1
count = 2
count = 3
count = 4


while loops


var i = 0
while i++ < 5 {
    println("\(i)")

}

//Console output:
1
2
3
4
5

do-while

do {
    println("\(i--)")

} while i > 0
//Console output:
6
5
4
3
2
1

Tuesday, July 1, 2014

Dictionaries

Dictionaries

Dictionary<KeyType, ValueType>

var pitchers = [
    "Wang": 40,
    "Kuo": 56,
]

Add new item
pitchers["Chen"] = 16

//pitchers =["Kuo": 56, "Wang": 40, "Chen": 16]

println("There are \(pitchers.count) pitchers in the dictionary.")
//Console output: There are 3 pitchers in the dictionary.

Change item value

pitchers["Kuo"] = 00

//pitchers =["Kuo": 0, "Wang": 40, "Chen": 16]

for loop: Iterating Over the dictionary

for (surname, number) in pitchers {
    println("\(surname): \(number)")
}

//Console output: 
Kuo: 0
Wang: 40
Chen: 16

for surname in pitchers.keys {
    println("Pitcher Surname: \(surname)")
}

for number in pitchers.values {
    println("Pitcher Number: \(number)")
}

//Console output:
Pitcher Surname: Kuo
Pitcher Surname: Wang
Pitcher Surname: Chen
Pitcher Number: 0
Pitcher Number: 40
Pitcher Number: 16

================================

Declare an empty dictionary
var airlineCode = Dictionary<String, String>()

println("There are \(airlineCode.count) data.")

var airlineCode = [String: String]()


//Console output: There are 0 data.
//The first line may be written as the shortcut format var airlineCode = [String: String]()

Add new item
airlineCode["EVA Air"] = "BR"
//airlineCode = ["EVA Air": "BR"]

Reset the dictionary
airlineCode = [:]