Swift 语法:控制流(Control Flow)

转载请声明出处:http://blog.csdn.net/jinnchang/article/details/43233427

1、For 循环

// 使用 for-in 进行遍历
for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")
}

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    println("Hello, \(name)!")
}

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    println("\(animalName)s have \(legCount) legs")
}

for character in "Hello" {
    println(character)
}

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}

// 使用 For 条件递增进行遍历
for var index = 0; index < 3; index++ {
    println("index is \(index)")
}

var index: Int
for index = 0; index < 3; ++index {
    println("index is \(index)")
}

2、While 循环

var countOne = 3
while countOne < 2 {
    countOne += 3
}
println("The countOne is now \(countOne)")
// prints "The countOne is now 3"

var countTwo = 3
do {
    countTwo += 3
} while countTwo < 2
println("The countTwo is now \(countTwo)")
// prints "The countOne is now 6"

3、If 条件语句

let temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    println("It's really warm. Don't forget to wear sunscreen.")
} else {
    println("It's not that cold. Wear a t-shirt.")
}
// prints "It's not that cold. Wear a t-shirt." 

4、Switch 条件语句

在 Swift 中,当匹配的 case 块中的代码执行完毕后,程序会终止 switch 语句,而不会继续执行下一个 case 块,不需要在 case 块中显式地使用 break 语句。
// switch 的简单形式 
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    println("\(someCharacter) is a vowel")
default:
    println("\(someCharacter) is not a vowel")
}
// prints "e is a vowel"

// switch 的范围匹配
let age = 45  
switch age { 
case 0...5: 
    println("It's a baby.")
case 6...18: 
    println("It's a teenager.")
case 19...55: 
    println("It's an adult.")
default: 
    println("It's an old people.")
} 
// prints "It's an adult." 
(1)switch 中的元组
switch 的元组中的元素可以是值,也可以是范围,也可使用下划线(_)来匹配所有可能的值。

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    println("(0, 0) is at the origin")
case (_, 0):
    println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
    println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
    println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box"
(2)switch 值绑定
case 块允许将匹配的值绑定到一个临时的常量或变量上,在对应的 case 块里就可以引用这个常量或者变量。

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    println("on the x-axis with an x value of \(x)")
case (0, let y):
    println("on the y-axis with a y value of \(y)")
case let (x, y):
    println("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value of 2"
(3)switch 中的 where 语句
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    println("(\(x), \(y)) is just some arbitrary point")
}
// prints "(1, -1) is on the line x == -y"

5、控制转移语句

Swift 有四种控制转移语句:continue、break、fallthrough、return。
(1)Continue
告诉循环体停止本次循环迭代,重新开始下次循环迭代。

// 找出1-50中既是6的倍数又是7的倍数的数
for(var i = 1; i < 50; i++){
    if(i % 6 != 0) {
        continue
    }
    if(i % 7 == 0) {
        println("\(i) is a multiple of 6 and 7")
    }
}
// prints "42 is a multiple of 6 and 7"
(2)Break
中断循环体的执行。

// 判断单词中是否包含字母L
let letter = "HELLO"
var isLetterContainL = false
for character in letter {
    if(character == "L") {
        isLetterContainL = true
        break
    }
}
(3)Fallthrough
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also"
    fallthrough
default:
    description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer."
(4)Return
return 语句在函数一文中讨论。
(5)标签语句
使用标签来标记一个循环体或者 switch 代码块,当使用 break 或者 continue 时,带上这个标签,可以控制该标签代表对象的中断或者执行。

// 检查数组(该数组元素限定为0-50之间的整数)中是否包含1到20之间的质数
var numbers = [6,23,17,20]
myLoop: for number in numbers {
    switch number {
    case 20...50:
        continue myLoop
    case 1,2,3,5,7,11,13,17,19:
        println("numbers has a prime of \(number).")
        break myLoop
    default:
        break
    }
}
// prints "numbers has a prime of 17."

6、结语

文章最后更新时间:2015年1月29日09:28:18。
欲了解更细致的请参考官方文档:Control Flow

你可能感兴趣的:(swift,flow,control,控制流,Playgrounds)