Swift4 基礎(chǔ)部分:Control Flow

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹楼镐,主要介紹Swift中的一些特性或者與OC差異點(diǎn)。

系列文章:

While

Repeat-While

The repeat-while loop in Swift is analogous to a do-while 
loop in other languages.
  • Swift中repeat-while的邏輯類似其他語言中do-while绵患,也是搞不懂Swift為什么要自己寫一套句灌。

例子:

repeat{
    print("invoked");
}while(false);

執(zhí)行結(jié)果:

invoked

Switch

In its simplest form, a switch statement compares a value
against one or more values of the same type.
  • Switch中的一個(gè)case語句可以寫入一個(gè)或者多個(gè)同類型的值。

例子:

func distinguishNumber(number: Int){
    switch number{
        case 2, 4, 6:
            print("\(number) is even");
        case 1, 3, 5:
            print("\(number) is odd");
        default:
            print("\(number) is exceed");
    }
}
distinguishNumber(number: 2);
distinguishNumber(number: 3);
distinguishNumber(number: 8);

執(zhí)行結(jié)果:

2 is even
3 is odd
8 is exceed

不存在隱式穿透(No Implicit Fallthrough)

In contrast with switch statements in C and Objective-C, 
switch statements in Swift do not fall through the bottom 
of each case and into the next one by default. Instead, 
the entire switch statement finishes its execution as soon 
as the first matching switch case is completed, without 
requiring an explicit break statement. This makes the 
switch statement safer and easier to use than the one in C 
and avoids executing more than one switch case by mistake.
  • Swift與OC,C中關(guān)于Swich中存在差異料身,Swift中默認(rèn)匹配到執(zhí)行的case,執(zhí)行完成直接break汤纸,而其他的語言O(shè)C,C必須加入顯式的break才能跳出。

例子直接參考上述的例子即可芹血。

Interval Matching(間隔匹配)

Values in switch cases can be checked for their inclusion in an 
interval
  • Swich case中的匹配值可以是區(qū)間類型數(shù)據(jù)贮泞。

例子:


func distinguishNumber(number: Int){
    switch number{
        case 1...10:
            print("\(number) <= 10");
        case 10...Int.max:
            print("\(number) > 10");
        default:
            print("\(number) is exceed");
    }
}
distinguishNumber(number: 2);
distinguishNumber(number: 13);

執(zhí)行結(jié)果:

2 <= 10
13 > 10

Tuples

You can use tuples to test multiple values in the same 
switch statement. Each element of the tuple can be tested 
against a different value or interval of values. 
Alternatively, use the underscore character (_), also 
known as the wildcard pattern, to match any possible 
value.
  • Swich case中也可以使用元組楞慈,元組中的值也可以是區(qū)間類型數(shù)據(jù)。

例子:

func distinguishPostion(x: Int,y :Int){
    let somePoint = (x, y)
    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")
    }
}

distinguishPostion(x: 0, y: 0);
distinguishPostion(x: 1, y: 1);

執(zhí)行結(jié)果:

(0, 0) is at the origin
(1, 1) is inside the box

Value Bindings

A switch case can name the value or values it matches to 
temporary constants or variables, for use in the body of 
the case. This behavior is known as value binding, because 
the values are bound to temporary constants or variables 
within the case’s body.
  • Switch case中可以寫入臨時(shí)的變量綁定傳入的值啃擦。

例子:

func distinguishPostion(x: Int,y :Int){
    let somePoint = (x, y)
    switch somePoint {
    case (0, 0):
        print("\(somePoint) is at the origin")
    case (let tempX, 0):
        print("\(somePoint) is on the x-axis,and x is \(tempX)")
    case (0, let tempY):
        print("\(somePoint) is on the y-axis,and y is \(tempY)")
    case (-2...2, -2...2):
        print("\(somePoint) is inside the box")
    default:
        print("\(somePoint) is outside of the box")
    }
}

distinguishPostion(x: 1, y: 0);
distinguishPostion(x: 0, y: 1);

執(zhí)行結(jié)果:

(1, 0) is on the x-axis,and x is 1
(0, 1) is on the y-axis,and y is 1

Where

A switch case can use a where clause to check for additional 
conditions.
  • Switch case中可以使用where 語句去做額外的條件判斷囊蓝。

例子:


func distinguishPostion(x: Int,y :Int){
    let somePoint = (x, y)
    switch somePoint {
    case let (x, y) where x == y:
        print("\(somePoint) is on the line x == y")
    case let (x, y) where x == -y:
        print("\(somePoint) is on the line x == -y")
    case let (x, y):
        print("\(somePoint) is just some arbitrary point")
    }
}

distinguishPostion(x: 0, y: 0);
distinguishPostion(x: 1, y: -1);
distinguishPostion(x: 0, y: 1);

執(zhí)行結(jié)果:

(0, 0) is on the line x == y
(1, -1) is on the line x == -y
(0, 1) is just some arbitrary point

Control Transfer Statements(控制轉(zhuǎn)移狀態(tài))

Control transfer statements change the order in which your 
code is executed, by transferring control from one piece 
of code to another. Swift has five control transfer 
statements:

continue
break
fallthrough
return
throw 
  • Swift中存在5種控制轉(zhuǎn)移狀態(tài),即以上的5種令蛉。

我們重點(diǎn)了解fallthrough,throw的使用聚霜。

Fallthrough

In Swift, switch statements don’t fall through the bottom 
of each case and into the next one. That is, the entire 
switch statement completes its execution as soon as the 
first matching case is completed. By contrast, C requires 
you to insert an explicit break statement at the end of 
every switch case to prevent fallthrough. Avoiding default 
fallthrough means that Swift switch statements are much 
more concise and predictable than their counterparts in C, 
and thus they avoid executing multiple switch cases by 
mistake.

If you need C-style fallthrough behavior, you can opt in 
to this behavior on a case-by-case basis with the 
fallthrough keyword. The example below uses fallthrough to 
create a textual description of a number.

  • Switch case如果需要能當(dāng)首個(gè)case執(zhí)行完能執(zhí)行到第二個(gè)case中必須加入Fallthrough關(guān)鍵字。

例子:

func distinguishPostion(x: Int,y :Int){
    let somePoint = (x, y)
    switch somePoint {
    case let (x, y) where x == y:
        print("\(somePoint) is on the line x == y")
        fallthrough;
    case let (_, 1):
        print("\(somePoint) is on the line y == 1")
    case let (x, y):
        print("\(somePoint) is just some arbitrary point")
    }
}

distinguishPostion(x: 1, y: 1);
distinguishPostion(x: 1, y: -1);
distinguishPostion(x: 0, y: 1);

執(zhí)行結(jié)果:

(1, 1) is on the line x == y
(1, 1) is on the line y == 1
(1, -1) is just some arbitrary point
(0, 1) is on the line y == 1
The fallthrough keyword does not check the case conditions 
for the switch case that it causes execution to fall into. 
The fallthrough keyword simply causes code execution to 
move directly to the statements inside the next case (or 
default case) block, as in C’s standard switch statement 
behavior.
  • fallthrough的關(guān)鍵字不會(huì)去檢查case中的條件判斷珠叔,寫了條件判斷也無效蝎宇。

例子:上述例子我們執(zhí)行distinguishPostion(x: 1, y: 2);結(jié)果不變。

標(biāo)記語言(Labeled Statements)

In Swift, you can nest loops and conditional statements 
inside other loops and conditional statements to create 
complex control flow structures. However, loops and 
conditional statements can both use the break statement to 
end their execution prematurely. Therefore, it is 
sometimes useful to be explicit about which loop or 
conditional statement you want a break statement to 
terminate. Similarly, if you have multiple nested loops, 
it can be useful to be explicit about which loop the 
continue statement should affect.

To achieve these aims, you can mark a loop statement or 
conditional statement with a statement label. With a 
conditional statement, you can use a statement label with 
the break statement to end the execution of the labeled 
statement. With a loop statement, you can use a statement 
label with the break or continue statement to end or 
continue the execution of the labeled statement.
  • Swift 中標(biāo)記語言這里說的很明白祷安,就是多層循環(huán)中可以利用標(biāo)記結(jié)合break,continue達(dá)到很方便結(jié)束標(biāo)記的某個(gè)循環(huán)邏輯姥芥。

例子:

let xLimitNum :Int = 20;
let yLimitNum :Int = 6;
var xSum :Int = 0;
var ySum :Int = 0;

xLoop:for x in 1...4{
    ySum = 0;
    yLoop:for y in 1...4{
        
        if ySum + y > yLimitNum{
            print("ySum:\(xSum) + y:\(y) > \(yLimitNum) break yLoop");
            break yLoop;
        }
        
        if xSum + y > xLimitNum{
            print("xSum:\(xSum) + y:\(y) > \(xLimitNum) break xLoop");
            break xLoop;
        }
        
        ySum += y;
        xSum += y;
        print("xSum:\(xSum - y) + y:\(y) = \(xSum)");
        print("ySum:\(ySum - y) + y:\(y) = \(ySum)");
    }
}

執(zhí)行結(jié)果:

xSum:0 + y:1 = 1
ySum:0 + y:1 = 1
xSum:1 + y:2 = 3
ySum:1 + y:2 = 3
xSum:3 + y:3 = 6
ySum:3 + y:3 = 6
ySum:6 + y:4 > 6 break yLoop
xSum:6 + y:1 = 7
ySum:0 + y:1 = 1
xSum:7 + y:2 = 9
ySum:1 + y:2 = 3
xSum:9 + y:3 = 12
ySum:3 + y:3 = 6
ySum:12 + y:4 > 6 break yLoop
xSum:12 + y:1 = 13
ySum:0 + y:1 = 1
xSum:13 + y:2 = 15
ySum:1 + y:2 = 3
xSum:15 + y:3 = 18
ySum:3 + y:3 = 6
ySum:18 + y:4 > 6 break yLoop
xSum:18 + y:1 = 19
ySum:0 + y:1 = 1
xSum:19 + y:2 > 20 break xLoop

注意標(biāo)記:xLoop,yLoop

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市汇鞭,隨后出現(xiàn)的幾起案子凉唐,更是在濱河造成了極大的恐慌,老刑警劉巖霍骄,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件熊榛,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡腕巡,警方通過查閱死者的電腦和手機(jī)玄坦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绘沉,“玉大人煎楣,你說我怎么就攤上這事〕瞪。” “怎么了择懂?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)另玖。 經(jīng)常有香客問我困曙,道長(zhǎng),這世上最難降的妖魔是什么谦去? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任慷丽,我火速辦了婚禮,結(jié)果婚禮上鳄哭,老公的妹妹穿的比我還像新娘要糊。我一直安慰自己,他們只是感情好妆丘,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布锄俄。 她就那樣靜靜地躺著局劲,像睡著了一般。 火紅的嫁衣襯著肌膚如雪奶赠。 梳的紋絲不亂的頭發(fā)上鱼填,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音毅戈,去河邊找鬼剔氏。 笑死,一個(gè)胖子當(dāng)著我的面吹牛竹祷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播羊苟,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼塑陵,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了蜡励?” 一聲冷哼從身側(cè)響起令花,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎凉倚,沒想到半個(gè)月后兼都,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡稽寒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年扮碧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片杏糙。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡慎王,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出宏侍,到底是詐尸還是另有隱情赖淤,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布谅河,位于F島的核電站咱旱,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏绷耍。R本人自食惡果不足惜吐限,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望褂始。 院中可真熱鬧毯盈,春花似錦、人聲如沸病袄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至脑奠,卻和暖如春基公,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背宋欺。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工轰豆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人齿诞。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓酸休,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親祷杈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子斑司,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

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

  • [The Swift Programming Language 中文版]本頁(yè)包含內(nèi)容: Swift提供了多種流程控...
    風(fēng)林山火閱讀 565評(píng)論 0 0
  • Swift 提供了類似 C 語言的流程控制結(jié)構(gòu),包括可以多次執(zhí)行任務(wù)的for和while循環(huán)但汞,基于特定條件選擇執(zhí)行...
    窮人家的孩紙閱讀 703評(píng)論 1 1
  • Swift提供了多種控制流聲明宿刮。包括while循環(huán)來多次執(zhí)行一個(gè)任務(wù);if私蕾,guard和switch聲明來根據(jù)確定...
    BoomLee閱讀 1,950評(píng)論 0 3
  • Swift 介紹 簡(jiǎn)介 Swift 語言由蘋果公司在 2014 年推出僵缺,用來撰寫 OS X 和 iOS 應(yīng)用程序 ...
    大L君閱讀 3,212評(píng)論 3 25
  • 這兩天忙的暈頭轉(zhuǎn)向容贝,晚上坐到電腦前的時(shí)候揉抵,已經(jīng)是11點(diǎn)了。 老婆坐在床上嗤疯,講起了今天的事冤今,主題只有一個(gè),就是我的家...
    快樂糊涂蟲閱讀 210評(píng)論 0 0