let arr = ["A","B","C"]
for value in arr {
print(value)
}
let dic = ["key":"a","key1":"b"]
for (key,value) in dic {
print("\(key)---\(value)")
}
for index in 1 ..< 3 {
print(index)
}
var a = 2
let b = 3
for _ in 1 ... b {
a += b
}
print(a)
//stride(from:to:by:)封闭范围是个开区间
for value in stride(from: 0, to: 10, by: 2) {
print(value) //0 2 4 6 8
}
//stride(from:through:by:)封闭范围是个闭区间
for value in stride(from: 0, through: 10, by: 2) {
print(value) //0 2 4 6 8 10
}
var a = 3
while a > 0 {
a -= 1
print(a) //2 1 0
}
var a = 0
repeat {
a += 1
print(a) //1 2 3
} while a < 3
let value = 5
if value > 3 {
print("\(value) is big than 3")
}
if value > 6 {
print("\(value) is big than 6")
}else{
print("\(value) is smaller than 6")
}
switch
let value = 2
switch value {
case 1:
print(value)
case 2:
print(value)
case 3:
print(value)
default:
print(value)
}
let value = 2
switch value {
case 1:
print(value)
case 2 , 3:
print(value)
default:
print(value)
}
switch value {
case 1:
print(value)
case 2 ..< 9:
print(value)
case 10:
print(value)
default:
print(value)
}
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) 原点")
case (_, 0):
print("\(somePoint) 在x轴上")
case (0, _):
print("\(somePoint) 在y轴上")
case (-2...2, -2...2):
print("\(somePoint) 在区域里")
default:
print("\(somePoint) 在区域外")
}
let anotherPoint = (0, 2)
switch anotherPoint {
case (let x, 0):
print("x 轴的值是 \(x)")
case (0, let y):
print("y 轴的值是 \(y)")
case let (x, y):
print("点的坐标是 (\(x), \(y))")
}
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 线上")
case let (x, y):
print("(\(x), \(y)) 只是任意一点")
}
let stillAnotherPoint = (9, 1)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("\(distance) 在轴上")
default:
print("不是在轴上")
}
let flag = 5
var description = "北京"
switch flag {
case 5:
description += "的"
fallthrough
case 10:
description += "冬天"
default:
description += "全是霾"
}
print(description) //北京的冬天
if...else
的地方都能使用guard...else
,但是反过来未必。guard一定要和else一起使用,而且使用的地方也必须是在函数中guard *判断语句* else {
*****
break\return\continue...
}
语句组
let score = 59
guard score >= 60 else {
print("考试不及格") // 不满足就返回
return
}
print(score)
整个流程都是比较清晰的,而且代码量也比if嵌套的少
if #available(platform name version, ..., *) {
APIs 可用,语句将执行
} else {
APIs 不可用,语句将不执行
}
iOS
,macOS
,watchOS
和tvOS
。除了指定像 iOS 8 或 macOS 10.10 的大版本号,也可以指定像 iOS 8.3 以及 macOS 10.10.3 的小版本号if #available(iOS 12, macOS 10.12, *) {
print("在 iOS 使用 iOS 12 的 API, 在 macOS 使用 macOS 10.12 的 API")
} else {
print("使用先前版本的 iOS 和 macOS 的 API")
}
if语句的代码块仅仅在 iOS 10 或 macOS 10.12 及更高版本才运行。最后一个参数,*,是必须的,用于指定在所有其它平台中,如果版本号高于你的设备指定的最低版本,if语句的代码块将会运行