Swift语法_控制流

  • Swift 提供了类似 C 语言的流程控制结构,包括可以多次执行任务的 for 和 while 循环,基于特定条件选择执 行不同代码分支的 if 、 guard 和 switch 语句,还有控制流程跳转到其他代码的 break 和 continue 语句。

  • 除了 C 语言里面传统的 for 循环,Swift 还增加了 for-in 循环,用来更简单地遍历数组(array),字典(dic
    tionary),区间(range),字符串(string)和其他序列类型。

  • Swift 的 switch 语句比 C 语言中更加强大。在 C 语言中,如果某个 case 不小心漏写了 break ,这个 case就会贯穿至下一个 case, Swift 无需写 break ,所以不会发生这种贯穿的情况。case 还可以匹配更多的类型模式,包括区间匹配(range matching),元组(tuple)和特定类型的描述。 switch 的 case 语句中匹配的值可 以是由 case 体内部临时的常量或者变量决定,也可以由 where 分句描述更复杂的匹配条件。


For-In

作用:循环来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符。

//for-in 闭包区间
for index in 1...5 {
    print("\(index) * 5 = \(index * 5)")
}

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

//for-in 遍历一个数组所有元素
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}

//for-in 遍历一个字典所有元素
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}

//for-in 遍历字符串内所有元素
let str = "yyuiognkagk"
for c in str.characters{
print(c, terminator:" ")
}

For

作用:使用条件判断和递增方法遍历

var index: Int
for index = 0; index < 3; ++index {
    print("index is \(index)")// index 在循环结束后最终的值是 3 而不是 2
}

while

  • 作用:适合使用在第一次迭代前迭代次数未知的情况下。

Swift 提供两种 while 循环形式
• while循环,每次在循环开始时计算条件是否符合;
• repeat-while循环,每次在循环结束时计算条件是否符合。
• 类似其他语言中的 do-while 循环

if

  • 条件较少时应用的条件语句

switch

  • 条件较多时应用的条件语句
  • 特点:必须是完备的(1…2…default,涵盖所有情况)
  • 区别:不同于其他语言,不存在隐式的贯穿,也就是说 当匹配的 case 分支中的代 码执行完毕后,程序会终止 switch 语句,而不会继续执行下一个 case 分支。也就是说在Swift中 break 不是必须的。
    注意:每一个 case 分支都必须包含至少一条语句(注释不算语句)
//1:每一个 case 分支都必须包含至少一条语句,否则报错
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
//    print("The letter a")
        break//救场
case "A":
    print("The letter A")
default:
    print("Not the letter")
}
//2:区间匹配,多条件匹配
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5,12..<100: //多条件用,隔开
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
//3:元组
//我们可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划 线( _ )来匹配所有可能的值。

//不像 C 语言,Swift 允许多个 case 匹配同一个值。
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("(0, 0) is at the origin")
case (_, 0):
    print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
    print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
    print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
//4:值绑定(Value Bindings)
//case 分支的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用了——这种行为被称为值绑定(value binding)。
//此栗子switch 语句已经完备了,因此不需要再书写默认分支以确保完备
let anotherPoint = (2, 1)
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))")
}
//5:where
//case 分支的模式可以使用 where 语句来判断额外的条件。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y://where判断额外的条件,进而进一步区分了
    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")
}
  • 控制转移语句(Control Transfer Statements)
  • 作用:控制转移语句改变你代码的执行顺序,通过它你可以实现代码的跳转

    Swift 有五种控制转移语句:
    • continue
    • break
    • fallthrough
    • return
    • throw

//continue 语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已 经执行完了”,但是并不会离开整个循环体。
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
    switch character {
    case "a", "e", "i", "o", "u", " ":
        continue//本次循环迭代结束,从新开始下次循环迭代
    default:
        puzzleOutput.append(character)
    }
}
print(puzzleOutput)
//break 语句会立刻结束整个控制流的执行。当你想要更早的结束一个 switch 代码块或者一个循环体时,你都可以 使用 break 语句。
/*
循环语句中的 break
当在一个循环体中使用 break 时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号( } )后的第 一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。
Switch 语句中的 break
当在一个 switch 代码块中使用 break 时,会立即中断该 switch 代码块的执行,并且跳转到表示 switch 代码块 结束的大括号( } )后的第一行代码。

注意: 当一个 switch 分支仅仅包含注释时,会被报编译时错误。注释不是代码语句而且也不能让 switch 分支 达到被忽略的效果。你总是可以使用 break 来忽略某个分支。
*/

let numberSymbol: Character = "三" // 简体中文里的数字 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).")
}
// 输出 "The integer value of 三 is 3."
//贯穿(Fallthrough)
//Swift 中的switch不像c语言中的case具有贯穿性,不会从上一个 case 分支落入到下一个 case 分支中,但是为了实现这种贯穿特性,swift研发了贯穿(Fallthrough)这种语法
//注意: fallthrough 关键字不会检查它下一个将会落入执行的 case 中的匹配条件。 fallthrough 简单地使代 码执行继续连接到下一个 case 中的执行代码,这和 C 语言标准中的 switch 语句特性是一样的。

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 a prime number, and also an integer."
/**
*  带标签的语句
   你可以使用标签来标记一个循环体或者 switch 代码块,当使用 break 或者 continue 时,带 上这个标签,可以控制该标签代表对象的中断或者执行。

*/

let finalSquare = 25
var board = [Int](count: finalSquare + 1, repeatedValue: 0)
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

gameLoop: while square != finalSquare {
    if ++diceRoll == 7 { diceRoll = 1 }
    switch square + diceRoll {
    case finalSquare:
        // 到达最后一个方块,游戏结束
        break gameLoop
    case let newSquare where newSquare > finalSquare:
        // 超出最后一个方块,再掷一次骰子
        continue gameLoop
    default:
        // 本次移动有效
        square += diceRoll
        square += board[square]
    } }
print("Game over!")

/*
注意:
如果上述的 break 语句没有使用 gameLoop 标签,那么它将会中断 switch 代码块而不是 while 循环体。使用 meLoop 标签清晰的表明了 break 想要中断的是哪个代码块。 同时请注意,当调用 continue gameLoop 去跳转到 下一次循环迭代时,这里使用 gameLoop 标签并不是严格必须的。因为在这个游戏中,只有一个循环体,所以 ntinue 语句会影响到哪个循环体是没有歧义的。然而, continue 语句使用 gameLoop 标签也是没有危害的。这 样做符合标签的使用规则,同时参照旁边的 break gameLoop ,能够使游戏的逻辑更加清晰和易于理解。
*/
/**
*  提前退出
*
*  像if语句一样, guard 的执行取决于一个表达式的布尔值。如果 guard 语句的条件被满足,则在保护语句的封闭大括号结束后继续执行代码。如果条件不被满足,在 else 分支上的代码就会被执行。

   不同于 if 语句,一个 guard 语句总是有一个 else 分句,如果条件不为真则执行else 分句中的代码。

   它可以用控制转移语句如 return , break , continue 或者 throw 做这件事,或者调用一个不返回的方法或函 数,例如 fatalError() 。

*/
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(["name": "John"])
// prints "Hello John!"
// prints "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// prints "Hello Jane!"
// prints "I hope the weather is nice in Cupertino."
/**
*  检测 API 可用性
*/

//if #available(platform name version, ..., *)
if #available(iOS 9, OSX 10.10, *) {
    // 在 iOS 使用 iOS 9 的 API, 在 OS X 使用 OS X v10.10 的 API
} else {
    // 使用先前版本的 iOS 和 OS X 的 API
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值