从零开始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{

    }

你可能感兴趣的:(从零开始Swift之控制流)