Swift 控制流(四)

Control Flow 控制流

For循环

for-in遍历一个集合里面的所有元素,index使用前不需要声明,只需包含在循环的声明中即可
for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
如果不知道区间内每一项的值,使用下划线 _ 来替代变量名去忽略,以下计算base的power次幂,这个例子不需要知道每一次循环中的具体值,只需知道需要循环的次数,使用下划线能够忽略具体的值,且不提供循环遍历时对值的访问
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049"

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

遍历字典

字典的每项以(key,value)元素组返回,在for-in循环中用显式的常量解读,因为字典是无序的,所以循环输出也是无序的

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

另一种for循环方式,条件判断和循环递增,执行顺序是先初始化 initialization,然后判断条件condition,如果为true执行语句statements,然后进行increment操作,再循环condition
for initialization; condition; increment {
    statements
}
//等同于
initialization
while condition {
    statements
    increment
}

for var index = 0; index < 3; ++index {
    println("index is \(index)")
}
// index is 0
// index is 1
// index is 2

While循环

适合在第一次条件未知的情况下使用,循环一直到条件变成false,两种形式,while , do-while
while condition {
    statements
}
//do-while形式就是在执行while里面的判断时,首先执行一次循环的代码,保证了循环至少执行一次
do {
    statements
} while condition
//翻译到这里原文好像开始玩起游戏来了。。。省略

条件语句

Swift提供if和switch语句,if用于条件简单且情况略少的时候,switch用于比较复杂和情况略多的时候

if: 只包含一个条件,条件为true,执行之

var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
    println("It's very cold. Consider wearing a scarf.")
}
// prints "It's very cold. Consider wearing a scarf."


temperatureInFahrenheit = 90
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 really warm. Don't forget to wear sunscreen."

switch:尝试把某个值与若干个条件进行比较,条件的值的类型都是相同的,switch语句由多个case构成,每个case都是代码的一条分支,在无法满足所有条件的情况下使用default
switch some value to consider {
case value 1:
    respond to value 1
case value 2,
value 3:
    respond to value 2 or 3
default:
    otherwise, do something else
}
当匹配的case执行完后,程序会终止switch语句,不再执行下一个case,所以可以省略break关键字
每个case必须包含至少一条语句,否则编译不通过,避免了从一个case分支贯穿到另一个case,让代码更安全
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
    println("The letter A")
default:
    println("Not the letter A")
}
// this will report a compile-time error

一个case也可以由多种情况,用逗号分开
switch some value to consider {
case value 1,
value 2:
    statements
}

case也可以用于区间
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
    naturalCount = "no"
case 1...3:
    naturalCount = "a few"
case 4...9:
    naturalCount = "several"
case 10...99:
    naturalCount = "tens of"
case 100...999:
    naturalCount = "hundreds of"
case 1000...999_999:
    naturalCount = "thousands of"
default:
    naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// prints "There are millions and millions of stars in the Milky Way."

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"

值绑定,在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"

在case里使用where,多加一个动态的过滤器,仅当case成立且where条件为true,才执行
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"

控制传递语句

控制代码的跳转,改变程序的执行顺序

continue
告诉一个循环体立刻停止本次循环,重新开始下一次循环
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
    switch character {
    case "a", "e", "i", "o", "u", " ":
        continue
    default:
        puzzleOutput += character
    }
}
println(puzzleOutput)
// prints "grtmndsthnklk"

break
结束当前循环
let numberSymbol: Character = "三"  // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
    possibleIntegerValue = 1
case "2", "٢", "二", "๒":
    possibleIntegerValue = 2
case "3", "٣", "三", "๓":
    possibleIntegerValue = 3
case "4", "٤", "四", "๔":
    possibleIntegerValue = 4
default:
    break
}
if let integerValue = possibleIntegerValue {
    println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    println("An integer value could not be found for \(numberSymbol).")
}
// prints "The integer value of 三 is 3."

贯穿 (Fallthrough)

Swift中的switch不会从上一个case里运行到下一个case里,只要第一个匹配的case执行完后,整个swtich代码就执行完了,而C语言需要break来防止这种现象,否则将会一直执行下去,如果需要C语言的这种特性,使用fallthrough关键字
fallthrough关键字不会检查它下一个落入执行case中的匹配条件,只会简单的使代码继续执行到下一个case中的代码
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."

带标签的语句 (Labeled Statements)

在循环体和switch代码中嵌套循环体和switch代码来创造复杂的控制流,因为都可以用break结束整个方法体,所以显式的指出需要终止哪个循环体或swtich是必要的,类似,显式指出continue想要影响哪个循环体也是有用的
通过使用标签来标记一个循环体或switch,标签后带一个冒号
label name: while condition {
    statements
}
以下例子来源于一个游戏例子,游戏的规则跟飞行棋类似,25个格子然后掷骰子,按掷的骰子走相应的步数,走到某些格子会前进几步或后退几步,走完25个或超过为赢家
let finalSquare = 25
var board = Int[](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0

gameLoop: while square != finalSquare {
    if ++diceRoll == 7 { diceRoll = 1 }
    switch square + diceRoll {
    case finalSquare:
        // diceRoll will move us to the final square, so the game is over
        break gameLoop
    case let newSquare where newSquare > finalSquare:
        // diceRoll will move us beyond the final square, so roll again
        continue gameLoop
    default:
        // this is a valid move, so find out its effect
        square += diceRoll
        square += board[square]
    }
}
println("Game over!")
如果上述的break语句没有使用标签,那将会中断switch而不是while,使用标签能清晰的表明break想要中断哪个循环

你可能感兴趣的:(ios,swift,苹果)