Swift4 基础部分:Control Flow

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

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);

执行结果:

invoked

Switch

In its simplest form, a switch statement compares a value
against one or more values of the same type.
  • Switch中的一个case语句可以写入一个或者多个同类型的值。

例子:

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);

执行结果:

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中关于Swich中存在差异,Swift中默认匹配到执行的case,执行完成直接break,而其他的语言OC,C必须加入显式的break才能跳出。

例子直接参考上述的例子即可。

Interval Matching(间隔匹配)

Values in switch cases can be checked for their inclusion in an 
interval
  • Swich case中的匹配值可以是区间类型数据。

例子:


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);

执行结果:

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中也可以使用元组,元组中的值也可以是区间类型数据。

例子:

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);

执行结果:

(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中可以写入临时的变量绑定传入的值。

例子:

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);

执行结果:

(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);

执行结果:

(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(控制转移状态)

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种控制转移状态,即以上的5种。

我们重点了解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如果需要能当首个case执行完能执行到第二个case中必须加入Fallthrough关键字。

例子:

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);

执行结果:

(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的关键字不会去检查case中的条件判断,写了条件判断也无效。

例子:上述例子我们执行distinguishPostion(x: 1, y: 2);结果不变。

标记语言(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 中标记语言这里说的很明白,就是多层循环中可以利用标记结合break,continue达到很方便结束标记的某个循环逻辑。

例子:

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

执行结果:

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

注意标记:xLoop,yLoop

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

推荐阅读更多精彩内容

  • [The Swift Programming Language 中文版]本页包含内容: Swift提供了多种流程控...
    风林山火阅读 529评论 0 0
  • Swift 提供了类似 C 语言的流程控制结构,包括可以多次执行任务的for和while循环,基于特定条件选择执行...
    穷人家的孩纸阅读 673评论 1 1
  • Swift提供了多种控制流声明。包括while循环来多次执行一个任务;if,guard和switch声明来根据确定...
    BoomLee阅读 1,888评论 0 3
  • Swift 介绍 简介 Swift 语言由苹果公司在 2014 年推出,用来撰写 OS X 和 iOS 应用程序 ...
    大L君阅读 3,128评论 3 25
  • 这两天忙的晕头转向,晚上坐到电脑前的时候,已经是11点了。 老婆坐在床上,讲起了今天的事,主题只有一个,就是我的家...
    快乐糊涂虫阅读 182评论 0 0