if else
while
var num = 5
while num > 0 {
print("num is \(num)")
num -= 1
}
var num = -1
repeat {
print("num is \(num)")
} while num > 0
repeat-while 相当于C语言中的do-while
这里不是num—,是因为Swift3开始,去除了自增(++)、自减(—)运算符
(阅读性较差)
for
闭区间运算符: a…b,a <= 取值 <= b
let names = ["a", "b", "c", "d"]
for i in 0...3 {
print(names[i])
}
或者 let range = 0…3, for i in range这样遍历
如果没有用到i,可以用下划线代替
for _ in 0...3 {
}
半开区间运算符:a..区间运算符用在数组上
for name in names[0...3] {
print(name)
}
单侧区间:让区间朝一个方向尽可能的远
for name in names[...3] {
print(name)
}
for name in names[..<3] {
print(name)
}
也可以将区间赋值给range
// 负无穷到5
let range = ...5
range.contains(7) // true
range.contains(3) // false
字符、字符串也能使用区间运算符,但默认不能在for-in中
let range = "a"..."z"
range.contains("c")
range.contains("e")
带间隔的区间值
/// 打印0-100间的偶数
for i in stride(from: 0, through: 100, by: 2) {
print(i)
}
switch
let num = 1
switch num {
case 1:
print("num is 1")
case 2:
print("num is 2")
case 3:
print("num is 3")
default:
print("num is other")
}
// num is 1
case、default后面不能写大括号{}
默认可以不写break,并不会贯穿到后面的条件
fallthrough,可以实现贯穿效果
let num = 1
switch num {
case 1:
print("num is 1")
fallthrough
case 2:
print("num is 2")
case 3:
print("num is 3")
default:
print("num is other")
}
// num is 1
// num is 2
switch必须保证能处理所有情况,下面这种情况不写default就会报错
case、default后面至少有一条语句,如果不想做任何事情,加个break即可
如果能保证处理所有情况,也不必使用default,例如枚举
enum Answer {
case right
case wrong
}
let answer = Answer.right
switch answer {
case .right:
print("answer is right ")
case .wrong:
print("answer is right ")
}
复合条件
switch也支持Character、String类型
let string = "Jack"
switch string {
case "Jack":
print("is jack")
case "Tom":
print("is Tom")
default:
break
}
复合条件可以使用逗号分隔条件,也可以用fallthrough关键字
switch name {
case "Jack", "Rose":
print("is Jack and Rose")
case "Tom":
print("is Tom")
default:
break
}
switch name {
case "Jack":
print("is jack")
fallthrough
case "Rose":
print("is Rose")
case "Tom":
print("is Tom")
default:
break
}
字符类型也一样:
let c: Character = "a"
switch c {
case "a":
print("is a")
case "A":
print("is A")
default
break
}
区间匹配、元组匹配
let count = 62
switch count {
case 1..<5:
print("1..<5")
case 6..<100:
print("6..<100")
default:
break
}
let point = (1, 1)
switch point {
case (0, 0):
print("is zero point")
case (_, 0):
print("is on x-axis")
case (0, _):
print("is on y-axis")
default:
break
}
可以使用下划线忽略某个值,case匹配问题,属于模式匹配(Pattern Matching)的范畴
值绑定
switch point {
case (let x, 0):
print("x is \(x)")
case (0, let y):
print("y is \(y)")
case let (x, y):
print("x is \(x), y is \(y)")
default:
break
}
where
在switch语句中作为条件
switch point {
case let (x, y) where x == y:
print("x == y")
case let (x, y) where x == -y:
print("x == -y")
default:
break
}
在for循环中作为条件
// 打印区间内所有的偶数
for i in -100...100 where i%2 == 0 {
print("i = \(i)")
}
标签语句
outer: for i in 0...3 {
for k in 0...3 {
if k == 3 {
continue outer
}
if i == 3 {
break outer
}
print("i = \(i), k = \(k)")
}
}