美文网首页iOS Developer
Swift语法学习笔记2:流程控制

Swift语法学习笔记2:流程控制

作者: xueyuios | 来源:发表于2016-08-17 10:44 被阅读0次

本篇是《Swift语法学习笔记》系列的第二篇文章,将涵盖以下内容:

  • 流程控制
- if语句
    - 一般使用方法
    - 三目运算符
    - 多个条件用逗号隔开
    - where详解
- for循环
    - 一般使用方法
    - 自定义递进序列
    - 遍历
- while语句
- repeat语句
- Switch语句
    - 一般使用方法
    - 字符串case分支

1 if语句

1.1 一般使用方法

Swift中的if语句必须包含一对花括号,即使只有一行语句。另外,if后紧跟的判断语句可以不用()括起来,具体如下所示:

let random = arc4random_uniform(10)
if random < 5 {
    print("Hi")
} else {
    print("Ho")
}

1.2 三目运算符

1.1小节的例子可以精简为:

let random = arc4random_uniform(10)
random < 5 ? print("Hi") : print("Ho")

或者

let random = arc4random_uniform(10)
print(random < 5 ? "Hi" : "Ho")

1.3 多个条件用逗号隔开

let dict = [0: "Red", 1: "Green", 2: "Blue", 3: "Green", 4: "Yellow"]
let color1 = dict[Int(arc4random_uniform(6))]
let color2 = dict[Int(arc4random_uniform(6))]
if let color1 = color1, color2 = color2 {
    // Executed only if both colors were not nil
    print("color1: \(color1), color2: \(color2)")
}

1.4 where详解

var optionName: String? = "Ricky"
if let name = optionName where name.hasPrefix("R"){
    print("\(name)")
}

例子中的if语句执行的是:把optionName的值赋予常量name,如果没有值将为false退出if。而where执行的是判断可选变量optionName的首字母是否为大写"R",如果为false将退出if。这两个语句放在一起时,可以理解为“&&”的条件。无论是前面的语句还是后面的where语句,只要其中一个不符合规则,将输出false退出if语句体。

2 for循环

2.1 一般使用方法

for var i = 0; i < 10; i++ {
    print(i)
}

或者

for i in 0..<10 {
    print(i)
}

在使用in格式的for循环时,循环条件的控制变量无需声明,可以直接使用。

2.2 自定义递进序列

需要用到“数字.stride”来产生递进序列:

1.stride(through: 5, by: 1)     // 1,2,3,4,5
1.stride(to: 5, by: 1)          // 1,2,3,4

应用到for循环中:

for i in 10.stride(through: 0, by: -2) {
    print(i)
}

2.3 遍历

遍历数组:

let strings = ["A", "B", "C"]
for string in strings {
    print(string)
}

遍历

Set:let strings = Set<String>(["A", "B", "C"])
for string in strings {
    print(string)
}

遍历字典:

let d = [ 0: "Red", 1: "Green", 2: "Blue"]
for key in d.keys {
    print("\(key) -> \(d[key])")
}

或者

for (key, value) in d {
    print("\(key) -> \(value)")
}

3 while语句

var i = 10
while i > 0 {
    print(i--)
}

4 repeat语句

var j = 10
repeat {
    print(j--)
} while j > 0

5 Switch语句

5.1 一般使用方法

let value = 11
switch value {
    case 2, 3, 5, 7, 11, 13, 17, 19:
        print("Count is prime and less than 20")
    case 20...30:
        print("Count is between 20 and 30")
    default:
        print("Greater than 30")
}
  • 建议使用default,因为假如在case中找不到任何的value的值,那么将会产生一个运行时错误;
  • 不允许使用空的case语句。

    switch (value) {
    case 2:
    case 3: // Illegal – previous case is empty.
    print("Value is 2 or 3")
    default:
    print("Value is neither 2 nor 3")
    }

上述代码是错误的,需要修正为:

switch (value) {
    case 2, 3:     // Correct: catches value 2 and value 3
        print("Value is 2 or 3")
    default:
        print("Value is neither 2 nor 3")
}

或者

switch (value) {
    case 2: fallthrough
    case 3:     // Illegal – previous case is empty.
        print("Value is 2 or 3")
    default:
        print("Value is neither 2 nor 3")
}

5.2 字符串case分支

let s = "Hello"
switch s {
    case "Hello":
        print("Hello to you, too")
    case "Goodbye":
        print("See you tomorrow")
    default:
        print("I don't understand")
}

或者

enum Status {
    case OK
    case ERROR(String)
}
let result = Status.ERROR("Network connection rejected")
switch (result) {
    case .OK:
        print("Success!")
    case .ERROR(let message):
        print("Ooops: \(message)")
}

由于编译器知道result是一个枚举类型,所以可以省略Status,但是不可以省略.。另外,编译器也知道这个枚举类型只有两个值,所以可以省略default语句。

参考文献

《Beginning iPhone Development with Swift 2 - Exploring the iOS SDK 》From page 777 to page 838.

联系作者

相关文章

网友评论

    本文标题:Swift语法学习笔记2:流程控制

    本文链接:https://www.haomeiwen.com/subject/eyjmsttx.html