if-else
let age = 4
if age >= 22 {
print("Get married")
} else if age >= 18 {
print("Being a adult")
} else if age >= 7 {
print("Go to school")
} else {
print("Just a child")
}
if后面的条件可以省略小括号
条件后的大括号不可以省略
if后面的条件只能是Bool类型
var num = 5
while num > 0 {
print("num is (num)")
num -= 1
}//打印了5次
var num = -1
repeat {
print("num is (num)")
} while num > 0//打印了一次
repeat-while相当于c语言中的do-while
这里不用num--,是因为从Swift开始,去除了自增(++),自减(--)运算符
for循环
闭区间运算符:a...b, a <= 取值 <= b
let names = ["Anna", "Alex", "Brian", "Jack"]
for i in 0...3 {
print(names[i])
}// Anna Alex Brian Jack
let rang = 1...3
for i in rang {
print(names[i])
}//Alex Brian Jack
let a = 1
let b = 2
for i in a...b {
print(names[i])
}//Alex Brian
for i in a...3 {
print(names[i])
}//Alex Brian Jack
for _ in 1...3 {
print("for")
}//打印了3次
i 默认是let, 有需要时可以声明为var
for var i in 1...3 {
i += 5
print(i)
}//6 7 8
半开区间运算符:a..<b, a <= 取值 < b
for i in 1..<5{
print(i)
}//1 2 3 4
for - 区间运算符用在数组上
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names[0...3] {
print(name)
}//Anna Alex Brian Jack
单侧区间:让区间炒一个方向尽可能的远
for name in names[2...]{
print(name)
}//Brian Jack
for name in names[...2]{
print(name)
}//Anna Alex Brian
for name in names[..<2] {
print(name)
}//Anna Alex
let range = ...5
range.contains(7) //false
range.contains(4) //true
range.contains(-3) //true
区间类型
let rang1: ClosedRange<Int> = 1...3
let rang2: Range<Int> = 1..<3
let rang3: PartialRangeThrough<Int> = ...5
字符,字符串也能使用区间运算符,但默认不能用在for-in中
let stringRange1 = "cc"..."ff"
stringRange1.contains("cb")//false
stringRange1.contains("dz")//true
stringRange1.contains("fg")//false
let stringRange2 = "a"..."f"
stringRange2.contains("d")//true
stringRange2.contains("h")//false