从零开始Swift之控制流

循环

For-In 循环

for index in 1...5 {
    print("\(index) times 5 is \(index * 5))")
}

For-In 遍历数组

let names = ["Anna","Alex","Brain","Jace"]
for name in names {
    print("\(name)");
}

while 循环

let finalSquare = 25
var board = [Int](repeatElement(0, count: finalSquare + 1))
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
while square < finalSquare {
    diceRoll += 1
    if diceRoll == 7 {
        diceRoll = 1
    }
    square += diceRoll
    if square < board.count {
        square += board[square];
    }
}
print("Game over!")

repeat-while循环, "while" 循环是线判断条件, 后执行循环体, repeat-while循环是先执行一次循环体, 然后判断条件, 再循环, 直到条件为假

//repeat {
//    ....
//} while ....

条件语句

if

var temperatureInfahrenheit = 30
if temperatureInfahrenheit <= 32 {
    print("It's very cold. consider waring a scarf")
}

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

Switch

swift中的switch 中case条件将不再仅仅限制于Int型, 多种类型都可以当做case条件

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

与 C 和 Objective-C 相反, Swift中的 switch 语句不会通过没一种情况, 默认情况下进入下一个语句. 相反, 整个switch语句在第一个匹配情况完成后立即完成执行, 而不需要break语句

每个case 后面必须接一个执行代码否则会报错

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

一次匹配多个条件, 多个条件现在一个case里, 使用","隔开

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a","A":
    print("The letter A")
default:
    print("Not the letter A")
}
// case 的条件可以是一个范围
let approxmateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approxmateCount {
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)")

使用元组当做条件

let somePoint = (1,1)
switch somePoint {
case (0,0):
    print("(0,0)在坐标原点上")
case (_,0):
    print("(\(somePoint.0),0) 在x轴上")
case (0,_):
    print("(0,\(somePoint.1) 在y轴上)")
case (-2...2,-2...2):
    print("(\(somePoint.0), \(somePoint.1) 在矩形里)")
default:
    print("(\(somePoint.0), \(somePoint.1) 在矩形外)")
}

上上述例子中,坐标点(0,0)可以匹配多个case, 但是在swift中只会执行第一个匹配的case,其他条件都将被忽略

switch case 值绑定

一个switch case 可以绑定一个或多个值匹配的临时常量或者变量, 用于case的主体. 此行为称为值绑定

let anotherPoint = (2,0)
switch anotherPoint {
case (let x, 0):
    print("在x轴上有一个x值是\(x)")
case (0, let y):
    print("在y轴上有一个y值是\(y)")
default:
    print("")
}

Where

switch case 可以使用where子句来检查附加条件

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x),\(y) 在 x == y的线上)")
case let (x, y) where x == -y:
    print("(\(x),\(y) 在 x == -y的线上)")
default:
    print("")
}

控制转移语句

控制转移语句通过将控制从一段代码转移到另一段代码来改变代码执行的顺序,Swift有五个控制转移语句

  • continue
  • break
  • fallthrough
  • return
  • throw

continue

就是告诉代码,当前代码已完成,进行下一次循环

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a","e","i","o","u"]
for character in puzzleInput.characters{
    if charactersToRemove.contains(character) {
        continue
    }else{
        puzzleOutput.append(character)
        // 结果是 grt mnds thnk lk
        
    }
}

break

break语句立即结束整个控制流语句的执行.break可以在switch或者循环中使用

当在循环语句中使用时,break立即结束循环的执行,并将控制转移到循环结束括号(})之后的代码。 不执行来自循环的当前迭代的进一步代码,并且不开始循环的进一步迭代。

当在switch语句中使用break时,break会立即结束switch语句并将控制转移到switch语句的闭包(})后的代码。

此行为可用于匹配和忽略switch语句中的一个或多个case。 因为Swift的switch语句是详尽的,不允许空的情况,有时需要故意匹配和忽略一个case,以使你的意图显式。 你可以通过将break语句写为你想要忽略的整个案例来做到这一点。 当该情况由switch语句匹配时,case中的break语句立即结束switch语句的执行。

let numberSymbol: Character = "三"
var possibleInterValue:Int?
switch numberSymbol {
case "1", "١", "一":
    possibleInterValue = 1
case "2","二":
    possibleInterValue = 2
case "3","三":
    possibleInterValue = 3
case "4","四":
    possibleInterValue = 4
default:
    break
}
if let integerValue = possibleInterValue {
    print("The integer value of \(numberSymbol) is \(integerValue).")
}else{
    print("An integer could not be found for \(numberSymbol)")
}

Fallthrough

Swift中的switch语句不会通过每个case的底部,并进入下一个。 相反,整个switch语句在第一个匹配大小写完成后立即完成执行。 相比之下,C要求在每个开关情况结束时插入一个明确的break语句,以防止fallthrough。 避免默认fallthrough意味着Swift switch语句比它们在C中的同行更简洁和可预测,因此他们避免错误地执行多个switch case。如果您需要C风格的突发行为,您可以根据具体情况选择采用关键字逐渐减少的行为。

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)
// The number 5 is prime number, and also an integer

在Swift中,可以在其他循环和条件语句中嵌套循环和条件语句,以创建复杂的控制流结构。然而,循环和条件语句都可以使用break语句来提前结束它们的执行。因此,有时需要明确关于哪个循环或条件语句希望break语句终止。同样,如果你有多个嵌套循环,显式地说明continue语句应该影响哪个循环是有用的。

为了实现这些目的,你可以用一个语句标记一个循环语句或条件语句。使用条件语句,可以使用带有break语句的语句标签来结束带标签语句的执行。使用循环语句,可以使用带有break或continue语句的语句标签来结束或继续执行带标签的语句。

带标签的语句通过将标签放置在与语句的介绍者关键字相同的行上,后跟冒号来指示

var count = 0
loop: while count < 10{
    count += 1
    if count == 5 {
        continue loop
    }
}

if let 与 guard let

if let / var 连用语法, 目的就是判断值,不是单纯的if

if let 连用, 判断对象的值是否为 nil {} 内一定有值, 可以直接使用, 不需要解包

if var 连用, {} 可以对值进行修改!

if var name = oName,
        let age = oAge{
        name = "老李"
        print(name + String(age))
    }

guard let 守护一定有值, 如果没有直接返回

guard let name = oName, let age  = oAge else {
        print("姓名或年龄为 nil")
        return
    
    }
    // 代码执行至此, name 和 age 一定有值!
    // 通常判断是否有值后, 会做具体的逻辑实现, 通常代码多!
    // 如果用 if let 凭空多了一层分支, guard 是降低分支层次的办法
    // guard 的语法是 Swift 2.0 推出的!
    print(name + String(age))

if letguard let命名技巧

  • ==使用同名的变量接收值, 在后续使用的都是非控制, 不需要解包==
  • ==好处, 可以避免起名字的烦恼==
func demo(name: String?, age: Int?) {
        guard let name = name, let age = age else {
            return
        }
        print(name + String(age))
    }

检查API的可用性

if #available(iOS 10, macOS 10.12, *){
    // 在iOS平台上只能使用iOS 10或更高版本的API,并且在macOS上只能使用macOS 10.12 或更高版本的API
}else{

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

推荐阅读更多精彩内容