Swift 控制流
Posted fgyong的开发日记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 控制流相关的知识,希望对你有一定的参考价值。
控制流
循环
//循环
let arr:[Any] = [0,1,2,3,4,5,6]
for i in arr{
print("hello \(i)")
}
设置步长的循环
// 设置步长
for i in stride(from: 0, to: arr.count, by: 2)
{
print(arr[i]) // 0 2 4 6
}
switch
let ch:Character = "1"
switch ch {
case "1": break
case "2": break
case "a": break
case "b": break
default:
break
}
多种数据组合
//多组合
switch ch{
case "a","b","c":break
case "d":break
default:break;
}
let i = 10
switch i {
case 0..<2:break
case 2..<4:break
default:
break
}
// 某个点在 某个区域
let somePoint = (1, 1)
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")
}
//值绑定
let anotherPoint = (2, 0)
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))")
}
// 添加条件语句
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
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")
}
标签
跳转到右标签的地方,在OC
消息发送的地方有此机制,可以更灵活的控制循环。
//标签
var a = 20
goto: while a > 10{
print(a)
a -= 1
continue goto
}
检查API可用性
这点在OC
和Swift
都可以使用的
if #available(platform name version, ..., *) {
statements to execute if the APIs are available
} else {
fallback statements to execute if the APIs are unavailable
}
•
以上是关于Swift 控制流的主要内容,如果未能解决你的问题,请参考以下文章
Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题