Swift教程之控制流

控制流

Swift包含很多控制流語句:while循環(huán)、if炎疆、guard、switch和for-in循環(huán)国裳。

<br />

For-In循環(huán)

for-in循環(huán)用于迭代序列形入,如數(shù)組遍歷、數(shù)字范圍缝左、字符串中的字符亿遂。

下面為for-in循環(huán)遍歷數(shù)組:

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

遍歷字典:

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

遍歷數(shù)字范圍:

for index in 1...5 {
    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

若不需要序列中的值時(shí)浓若,使用下劃線代替變量名來忽略這些值:

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

遍歷半開數(shù)字范圍:

let minutes = 60
for tickMark in 0..<minutes {
    // render the tick mark each minute (60 times)
}

使用stride(from:to:by:)方法跳過不需要的遍歷:

let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}

stride(from:through:by:)方法遍歷包括結(jié)尾值:

let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
    // render the tick mark every 3 hours (3, 6, 9, 12)
}

<br />

While循環(huán)

Swift有兩種while循環(huán):

  • 每次循環(huán)開始時(shí)判斷循環(huán)條件的while循環(huán)
  • 每次循環(huán)結(jié)束時(shí)判斷循環(huán)條件的repeat-while循環(huán)

While

while循環(huán)語法:

while condition {

    statements

}

Repeat-While

Swift的repeat-while循環(huán)與其他語言的do-while循環(huán)類似。

repeat-while循環(huán)語法:

repeat {

    statements

} while condition

<br />

條件語句

Swift提供兩種條件語句:ifswitch語句蛇数。if判斷簡單條件挪钓,可能結(jié)果較少;switch適合復(fù)雜條件且可能情況較多的情況耳舅,常用于模式匹配碌上。

If

Swift中的if語句可忽略判斷條件的括號(hào),但執(zhí)行語句的大括號(hào)不可或缺:

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

if-else語句:

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.")
}

多重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 {
    print("It's not that cold. Wear a t-shirt.")
}

Switch

switch語句比較多個(gè)匹配模式浦徊,且能匹配任意類型值馏予,語法如下:

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

}

switch語句必須列出所有可能情況。

下面例子匹配單個(gè)小寫字符:

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")
}

Swift的switch語句不需要在每個(gè)語句塊最后顯式使用break語句(也可使用)盔性。當(dāng)匹配某個(gè)條件時(shí)霞丧,之間結(jié)束執(zhí)行整個(gè)switch語句。

switch語句的每個(gè)條件必須只要包含一個(gè)可執(zhí)行語句冕香,否則會(huì)拋出編譯錯(cuò)誤:

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// This will report a compile-time error.

要將兩個(gè)判斷條件合并蛹尝,使用逗號(hào)隔開:

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}

注意

要想顯示跳過某次判斷條件,進(jìn)入下個(gè)條件悉尾,使用fallthrough關(guān)鍵字突那。

間隔匹配

使用間隔匹配可在一條判斷語句中匹配多個(gè)值:

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let 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).")
// Prints "There are dozens of moons orbiting Saturn."

匹配元組

使用元組可在一條switch語句中匹配復(fù)合值,并使用下劃線匹配元組中某個(gè)元素的所有可能值焕襟。

當(dāng)已經(jīng)匹配某個(gè)條件時(shí)陨收,之后的所有條件都將被忽略饭豹。
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("(somePoint) is at the origin")
case (_, 0):
print("(somePoint) is on the x-axis")
case (0, _):
print("(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("(somePoint) is inside the box")
default:
print("(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"

值綁定

值綁定表示將匹配到的值命名為臨時(shí)常量或變量鸵赖。

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
// Prints "on the x-axis with an x value of 2"

當(dāng)某個(gè)條件正好匹配所有可能的剩余情況時(shí),則default語句可忽略拄衰。

Where

使用where語句對(duì)某個(gè)case添加額外條件:

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

復(fù)合case

使用逗號(hào)在一個(gè)case匹配多個(gè)條件它褪,條件過長時(shí)可多行顯示:

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")
}
// Prints "e is a vowel"

復(fù)合匹配中也可包含值綁定:

let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
    print("On an axis, \(distance) from the origin")
default:
    print("Not on an axis")
}
// Prints "On an axis, 9 from the origin"

<br />

控制轉(zhuǎn)移語句

Swift有五種控制轉(zhuǎn)移語句:

  • continue
  • break
  • fallthrough
  • return
  • throw

Continue

continue語句表示在循環(huán)中跳過本次循環(huán),直接開始下一次循環(huán)翘悉,而不結(jié)束循環(huán):

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput {
    if charactersToRemove.contains(character) {
        continue
    } else {
        puzzleOutput.append(character)
    }
}
print(puzzleOutput)
// Prints "grtmndsthnklk"

Break

break語句立即結(jié)束執(zhí)行整個(gè)控制流語句茫打。

用于循環(huán)語句的break

當(dāng)在循環(huán)語句中使用break時(shí),break會(huì)立即結(jié)束執(zhí)行整個(gè)循環(huán)語句妖混。

用于switch語句的break

當(dāng)在switch語句中使用break時(shí)老赤,break會(huì)立即結(jié)束執(zhí)行整個(gè)switch

Swift的switch語句中不用顯示使用break跳出匹配制市,但可以在某個(gè)case中可以插入break結(jié)束匹配以使意圖明確抬旺。

let numberSymbol: Character = "三"  // Chinese symbol 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 {
    print("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    print("An integer value could not be found for \(numberSymbol).")
}
// Prints "The integer value of 三 is 3."

Fallthrough

Swift中,switch語句在匹配到某個(gè)case條件后會(huì)忽略之后所有case祥楣,不會(huì)自動(dòng)下一個(gè)case开财。若需要像C語言那樣跳入下個(gè)case中汉柒,可使用fallthrough關(guān)鍵字。

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."
}
print(description)
// Prints "The number 5 is a prime number, and also an integer."

注意

fallthrough關(guān)鍵字不會(huì)檢查下個(gè)進(jìn)入的case判斷條件责鳍,只是簡單地跳入下一個(gè)case并執(zhí)行內(nèi)部代碼碾褂,與C語言中的switch語句相似。

標(biāo)簽語句

當(dāng)使用循環(huán)或條件嵌套語句時(shí)历葛,需要明確說明要使用breakcontinue語句來結(jié)束哪層控制語句正塌,這時(shí)使用標(biāo)簽語句對(duì)需要提前結(jié)束的控制語句做標(biāo)簽,然后在breakcontinue語句后接上已聲明的標(biāo)簽名來結(jié)束帶相同標(biāo)簽的語句恤溶。語法如下:

label name: while condition {

    statements

}

<br />

guard語句

guard語句是if語句的變體传货,通過將判斷條件的主體執(zhí)行代碼放在guard語句末尾以使代碼意圖更加清晰。

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }
    
    print("Hello \(name)!")
    
    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(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."

<br />

檢查API可用性

Swift支持檢查API可用性宏娄,避免代碼中使用不可用API導(dǎo)致意外錯(cuò)誤问裕。

當(dāng)嘗試使用不可用API時(shí),Swift會(huì)報(bào)告編譯錯(cuò)誤孵坚。

if #available(iOS 10, macOS 10.12, *) {
    // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
    // Fall back to earlier iOS and macOS APIs
}

語法如下:

if #available(platform name version, ..., *) {

    statements to execute if the APIs are available

} else {

    fallback statements to execute if the APIs are unavailable

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末粮宛,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子卖宠,更是在濱河造成了極大的恐慌巍杈,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扛伍,死亡現(xiàn)場離奇詭異筷畦,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)刺洒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門鳖宾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人逆航,你說我怎么就攤上這事鼎文。” “怎么了因俐?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵拇惋,是天一觀的道長。 經(jīng)常有香客問我抹剩,道長撑帖,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任澳眷,我火速辦了婚禮胡嘿,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘境蔼。我一直安慰自己灶平,他們只是感情好伺通,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著逢享,像睡著了一般罐监。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上瞒爬,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天弓柱,我揣著相機(jī)與錄音,去河邊找鬼侧但。 笑死矢空,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的禀横。 我是一名探鬼主播屁药,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼柏锄!你這毒婦竟也來了酿箭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤趾娃,失蹤者是張志新(化名)和其女友劉穎缭嫡,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體抬闷,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡妇蛀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了笤成。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片评架。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖疹启,靈堂內(nèi)的尸體忽然破棺而出古程,到底是詐尸還是另有隱情蔼卡,我是刑警寧澤喊崖,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站雇逞,受9級(jí)特大地震影響荤懂,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜塘砸,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一节仿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧掉蔬,春花似錦廊宪、人聲如沸矾瘾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽壕翩。三九已至,卻和暖如春傅寡,著一層夾襖步出監(jiān)牢的瞬間放妈,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來泰國打工荐操, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留芜抒,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓托启,卻偏偏與公主長得像宅倒,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子屯耸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Swift 提供了類似 C 語言的流程控制結(jié)構(gòu)唉堪,包括可以多次執(zhí)行任務(wù)的for和while循環(huán),基于特定條件選擇執(zhí)行...
    窮人家的孩紙閱讀 706評(píng)論 1 1
  • Swift提供了多種控制流聲明肩民。包括while循環(huán)來多次執(zhí)行一個(gè)任務(wù)唠亚;if,guard和switch聲明來根據(jù)確定...
    BoomLee閱讀 1,958評(píng)論 0 3
  • 本章將會(huì)介紹 控制流For-In 循環(huán)While 循環(huán)If 條件語句Switch 語句控制轉(zhuǎn)移語句 continu...
    寒橋閱讀 727評(píng)論 0 0
  • [The Swift Programming Language 中文版]本頁包含內(nèi)容: Swift提供了多種流程控...
    風(fēng)林山火閱讀 571評(píng)論 0 0
  • 記得臨走前的前幾天,我仿佛還這就是平平常常的時(shí)候工窍,和過去的每一個(gè)悠閑的大學(xué)時(shí)光一樣割卖,只不過平常很一般的同學(xué)關(guān)系突...
    Yachilles閱讀 308評(píng)論 0 0