Swift 3.0之五、控制流

1. For-in 循环

使用 for...in 循环来遍历序列:

for index in 1...5 {  // index 是一个常量,它的值隐式地在循环中声明了,不需要再用let声明。
    print("\(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

如果不需要序列的每一个值,使用下划线来取代遍历名以忽略值:

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// 结果为: "3 to the power of 10 is 59049"

for...in 循环遍历数组元素:

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

for...in 循环遍历字典键值对:

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

2. While 循环

While 语句

while 循环的通用格式:

while condition {
    statements
}
// while 循环通过判断condition开始,如果 condition 为 true,大括号语句就重复执行到 condition 为 false。

如:

var index = 0
while index < 3 {
    print "index: \(index)"
    index += 1
}
// index: 0
// index: 1
// index: 2

Repeat-While 语句

Repeat-While 循环的通用格式:

repeat {
    statements
} while condition
// repeat-while 在判断 condition 之前已执行一次代码块。然后继续循环直到条件为 false 。

如:

var index = 0
repeat {
    print "index: \(index)"
    index += 1
}while index < 3
// index: 0
// index: 1
// index: 2

3. 条件语句

If 语句

最简单的形式:

var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
}
// 结果为: "It's very cold. Consider wearing a scarf."

else分句的if语句:

temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// 结果为: "It's not that cold. Wear a t-shirt."

带多个分支的if语句:

temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else { // 此 else 语句可以省略
    print("It's not that cold. Wear a t-shirt.")
}
// 结果为: "It's really warm. Don't forget to wear sunscreen."

Switch 语句

常见通用格式:

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对应的语句不能为空;符合某个case并执行完成此case对应的语句后,立即跳出switch语句。

字符或者字符串匹配,举个栗子:

let someCharacter: Character = "z"
switch someCharacter {
case "a":
    print("The first letter of the alphabet")
case "z":
    print("The last letter of the alphabet")
default:
    print("Some other character")
}
// 结果为: "The last letter of the alphabet"

区间匹配,举个栗子:

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// 结果为: "There are dozens of moons orbiting Saturn."

元组匹配,举个栗子:

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("(0, 0) is at the origin")
case (_, 0):             // 使用下划线来匹配所有可能的值
    print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):             // 使用下划线来匹配所有可能的值
    print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):   // 匹配某个区间
    print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// 结果为: "(1, 1) is inside the box"

匹配时值绑定,举个栗子:

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):  // 将匹配的值绑定给常量 x
    print("on the x-axis with an x value of \(x)")
case (0, let y):  // 将匹配的值绑定给常量 y
    print("on the y-axis with a y value of \(y)")
case let (x, y):  // 将匹配的值绑定给常量 x 和 y
    print("somewhere else at (\(x), \(y))")
}
// 结果为: "on the x-axis with an x value of 2"

使用 where 分句来检查额外的情况:

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:  // x == y 的情况
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y: // x == -y 的情况
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):                     
    print("(\(x), \(y)) is just some arbitrary point")
}
// 结果为: "(1, -1) is on the line x == -y"

多case情况下:

let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    print("\(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":
    print("\(someCharacter) is a consonant")
default:
    print("\(someCharacter) is not a vowel or a consonant")
}
//结果为: "e is a vowel"

4. 控制转移语句

Swift 拥有五种控制转移语句:

  • continue
  • break
  • fallthrough
  • return
  • throw

Continue 语句

continue语句告诉循环停止接下来要做的事情,并开始下一轮循环,举个例子:

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
    switch character {
    case "a", "e", "i", "o", "u", " ": // 遇到这些字符时,直接执行下一轮循环
        continue
    default:
        puzzleOutput.append(character)
    }
}
print(puzzleOutput)
// 结果为: "grtmndsthnklk"

Break 语句

Break立即跳出整体Switch或循环代码块:

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  // 默认情况下,立即跳出Swich语句
}
if let integerValue = possibleIntegerValue {
    print("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    print("An integer value could not be found for \(numberSymbol).")
}
// 结果为: "The integer value of 三 is 3."

Fallthrough 语句

Switch语句,默认符合某个case时跳出,不再匹配随后的case。但如果需要贯穿行为,可以在每个case末尾使用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  // fallthrough后,代码紧接着执行default中的语句。
default:
    description += " an integer."
}
print(description)
// 结果为: "The number 5 is a prime number, and also an integer."

给语句打标签

由于循环和条件语句可以相互内嵌,显式标明break或者coontinue具体哪个循环或者条件语句很有必要,因此可以为这个语句打个标签,通用格式为:

标签名字: 循环或Switch语句 {
    statements
}

举个栗子:

let finalSquare = 25
var square = 0
var diceRoll = 0

gameLoop: while square != finalSquare {  // 此处,为循环语句打了个gameLoop标签
    diceRoll += 1
    if diceRoll == 7 { diceRoll = 1 }
    switch square + diceRoll {
    case finalSquare:
        break gameLoop     // 如果不写gameLoop,跳出的是Switch语句而不是循环
    case let newSquare where newSquare > finalSquare:
        continue gameLoop  // 写不写gameLoop,没有区别
    default:
        square += diceRoll
        square += board[square]
    }
}
print("Game over!")

guard...else 语句

guard语句要求条件为真才能执行guard语句后的代码,否则只执行else中的语句:

注意: 1.else分支要用returnbreakcontinuethrow 或者一个无返回值的函数如fatalError()结尾。 2.guard条件中,使用可选项绑定而被赋值的变量或者常量,在整个guard代码块结束后中都是可用的。

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }
    
    print("Hello \(name)!")  // name 常量在guard代码块结束后仍然可以访问
    
    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }
    
    print("I hope the weather is nice in \(location).")
}

greet(["name": "John"])
// 结果为: "Hello John!"
// 结果为: "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// 结果为: "Hello Jane!"
// 结果为: "I hope the weather is nice in Cupertino."

#available 语句

对API可用性进行检查,如:

if #available(iOS 10, macOS 10.12, *) {
    // iOS平台使用iOS 10的API, macOS平台使用macOS 10.12的API。
} else {
    // 使用更早版本的API
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,812评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,626评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,144评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,052评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,925评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,035评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,461评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,150评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,413评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,501评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,277评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,159评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,528评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,868评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,143评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,407评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,615评论 2 335

推荐阅读更多精彩内容