跳转至

控制语句

控制语句

目录


1.条件语句

1.1if语句

略

1.2Switch语句

switch语句必须是完备的。这就是说,每一个可能的值都必须至少有case分支与之对应。在某些不可能含在所有值的情况下,你可以使用默认分支满足该要求,这个默认分支必须在switch语句最后面。

下面的例子使用switch语句来匹配一个名为someCharacter的小写字符

let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    println("\(someCharacter) is a consonant")
default:
    println("\(someCharacter) is not a vowel or a consonant")
}
// 输出 "e is a vowe
1.2.1不存在隐式的贯穿

与 C 语言和 Objective-C 中的switch语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句。

每一个case分支都必须包含至少一条语句。像下面这样书写代码是无效的,因为第一个case分支是空的。

1
2
3
4
5
6
7
8
9
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
    println("The letter A")
default:
    println("Not the letter A")
}
//这个将产生一个编译错误

一个case也可以包含多个模式,用逗号把它们分开,如果太长也可以分行写。

1
2
3
4
5
switch some value to consider {
case value 1,
value 2:
statements
}
1.2.2区间匹配

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).")
// 输出 "There are millions and millions of stars in the Milky Way."
1.2.3元组匹配

可以使用元组在同一个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")
}
// 输出 "(1, 1) is inside the box"
1.2.4值绑定

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))")
}
// 输出 "on the x-axis with an x value of 2"
1.2.5Where

case分支的模式可以使用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")
}
// 输出 "(1, -1) is on the line x == -y"

2.循环语句

2.1for循环

Swift提供了两种for循环形式

  • for-in用来遍历一个区间(range),序列(sequence),集合(collection),系列(progression)里面所有的元素执行一系列语句。
  • for条件递增(for-condition-increment)语句,用来重复执行一系列语句直到达成特定条件达成,一般通过在每次循环完成后增加计数器的值来实现。

for-in 循环

1
2
3
4
5
6
7
var sum = 0

for i in 1...100 {
    sum += i
}

println(sum)
如果你不需要知道区间内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问

1
2
3
4
5
6
7
8
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// 输出 "3 to the power of 10 is 59049"

for循环

1
2
3
4
5
6
7
var sum = 0

for var i = 0 ; i <= 100 ;i++ {
    sum += i
}

println(sum)

2.2while循环

1
2
3
4
5
6
7
8
9
var sum3 = 0

while index <= 100 {
    sum += index
    index++
}

println("sum=\(sum)")
// sum=5050

2.3dowhile循环

var index = 1

var sum = 0

do {
    sum4 += index
    index++
} while index <= 100

println("sum4=\(sum)")

3.控制转移语句

控制转移语句可以改变你代码的执行顺序,通过它可以实现代码的跳转。Swift有四种控制语句。

  • continue
  • break
  • fallthrough
  • return

3.1Continue语句

continue语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
    switch character {
    case "a", "e", "i", "o", "u", " ":
        continue
    default:
        puzzleOutput.append(character)
    }
}
println(puzzleOutput)
    // 输出 "grtmndsthnklk"

3.2break语句

break语句会立刻结束整个控制流的执行。

3.3Fallthrough

在case分支中使用fallthrough语句可以实现C语言的贯穿特性。

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)
// 输出 "The number 5 is a prime number, and also an integer."

3.4带标签的语句

可以使用标签来标记一个循环体或者switch代码块,当使用break或者continue时,带上这个标签,可以控制该标签代表对象的中断或者执行。

outer:for i in (1...5){
    for j in (1...5){

        if(i == 2){
            break outer;
        }
         println(j)
    }
}
//1
//2
//3
//4
//5

评论