SWIFT 2.控制流程

SWIFT 2.控制流程

For Loop

for idx in 1...5 {...}

for _ in 1...5 {...}

let a1 = [1,3,5]; for val in a1 {....} //for each item in array

let a2 = [1:"A", 2:"B", 3:"C"]; for (idx, val) in a2 {...} //for each item in dictionary

for ch in "ABC".characters {...} //for each character in a string

for var i=0; i<10;i++ {...}

While Loop

while idx < 5 {... ; idx++}

repeat {... } while (idx < 5)

Conditional Statements

if a==1 {

... 

} else if a ==2 {

...

} else {

...

}

switch val {

    case 1, 2, 3: 

       ...

    case 4,5:

      ...

    case 10...1000:

      ....

    default:

        ...

}

let point = (1,1) //Tuple

switch point {

    case (0 ,0):

         print("原點")

    case (_, 2):  // _ means anything

        print("\(point.0), 2")

    case (0, 0...3)

        print("X=0, Y between 0 to 3")

}

//value bindings

let man = ("ANN", 18)

switch man {

    case (let name, 0...20): 

        print("\(name) is young.")

    case let (name, age):

        print("\(name) is \(age).")

}

//Where condition

let man = ("ANN", 18)

switch man {

    case let (name, age) where age < 20: 

        print("\(name) is young.")

    case let (name, age):

        print("\(name) is \(age).")

}

Control Transfer 

continue : jump to next loop

breat : leave the loop

fallthrough : in switch, go to next "case" without check its condition

return : leave a function

Checking API availablility

 

if #available(iOS 9, OSX 10.10, *) {

    //API for iOS 9 and OS X 10.10 and newer

} else {

    //Use older API here

}

- Felix Lai