iOS开发Swift-控制流

1.For-In循环

复制代码
//集合循环
let names = ["a", "b", "c"]
for name in names {
    print("Hello, \(name)!")
}
//次数循环
for index in 1...5{
    print("Hello! + \(index)")
}
//不需要值时可以使用  _  来忽略此值
for _ in 1...5{
    print("Hello!")
}

2.while循环

复制代码
while a < b{  //直到a < b成为false时停止循环
    print(".")
}

3.Repeat-while循环

复制代码
repeat {
    print(".")
} while a < b    //先执行一次,然后a < b变成false时停止

4.If

复制代码
if a < b {
    //语句1
} else if a = b {
    //语句2
} else {
    //语句3
}

5.Switch

复制代码
Switch id {
    case "a":
        print("a")    //不需要加break,不存在隐式贯穿
    case "b":
        print("b")    //每种情况下必须包含语句,否则报错
    default:
        print("其他")
}

(1)复合匹配

复制代码
switch id {
    case "a", "b":   //如果写不下了可分行书写
        print("c")
    default:
        print("其他")
}

(2)区间匹配

复制代码
switch id {
    case 1..<5:
        print("1~4")
    case 5..12:
        print("5~11")
    default:
        print("其他")
}

(3)元组匹配

复制代码
switch somePoint {
    case (0,0):       //从上到下一一匹配,如果多个case都匹配的话只取最前面
        print("0,0")
    case (_,0):
        print("几,0")
    case (0,_):
        print("0,几")
    default:
        print("其他")
}

(4)值绑定匹配

复制代码
switch somePoint {
    case (let x, 0):
        print("\(x), 0")
    case (0, let y):
        print("0, \(y)")
    case let(x, y):
        print("\(x), \(y)")
}

(5)where

复制代码
switch yetPoint {
    case let (x, y) where x == y:
        print("\(x) == \(y)")
    case let (x, y) where x == -y:
        print("\(x) == - \(y)")
}

6.控制转移语句

continue, break, fallthrough, return, throw

continue: 停止本次循环,开始下次循环

break: 立即结束整个控制流。可以使用break忽略switch的分支。

fallthrough贯穿: switch中的case加入贯穿,case会穿透到下一个case/ default。

7.带标签的语句

复制代码
gameLoop: while a < b {
    a++
    switch a {
        case 1:
            continue gameLoop;
        case 2;
            break gameLoop;
        default:
            print("0")
    }
}

8.提前退出(guard)

复制代码
guard 语句 else {
    //不满足条件语句的时候运行此处代码块
    return/break/continue/throw/调用无返回方法或函数
}
//满足条件语句时运行此处代码块

9.检测API可用性

复制代码
if #available (iOS 10, macOS 10.12, *) {
    //iOS:平台名称。10:版本号。*:必须有,更高版本。
    //使用10版本API
} else {
    //使用之前版本的API
}
相关推荐
DONG91329 分钟前
Python 中的可迭代、迭代器与生成器——从协议到实现再到最佳实践
开发语言·汇编·数据结构·python·算法·青少年编程·排序算法
R-G-B38 分钟前
【C++ 初级工程师面试--4】形参带默认值的函数,特点,效率,注意事项
开发语言·c++·形参带默认值的函数·形参默认值特点,效率,注意事项·形参默认值特点·形参默认值效率·形参默认值注意事项
杂雾无尘1 小时前
解密 Swift 5.5 中的 @MainActor, 深入了解其优势与误区
ios·swift·客户端
Q_Q5110082851 小时前
python的驾校培训预约管理系统
开发语言·python·django·flask·node.js·php
路过看风景1 小时前
zsh: command not found: pod
ios·cocoapods
Dxy12393102161 小时前
Python正则表达式使用指南:从基础到实战
开发语言·python·正则表达式
吴Wu涛涛涛涛涛Tao1 小时前
SwiftUI 打造 TikTok 风格的滑动短视频播放器
ios·swiftui
YLCHUP1 小时前
题解:P4447 [AHOI2018初中组] 分组
开发语言·数据结构·c++·经验分享·算法·贪心算法·抽象代数
R-G-B2 小时前
【05】大恒相机SDK C#开发 —— Winform中采集图像并显示
开发语言·c#·大恒相机sdk·winform中采集图像·winform中采集图像并显示
三小尛2 小时前
C++友元
开发语言·c++·算法