swift 从入门到精通 二
2019-11-06 本文已影响0人
TAsama
if-else
let age = 4
if age >= 22 {
//to do
} else if age >= 18 {
//to do
} else if age >= 7 {
//to do
} else {
//to do
}
- if后面的条件可以省略小括号
- 条件后面的大括号不可以省略
- if后面的条件只能是Bool类型
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相当于语言中的do-while
- 这里不能使用num--, swift 中已经移除了 --/++ 语法,只能使用“-=/+=”
for
let names = ["Anna", "Alex", "Brian", "Jack"]
for i in 0...3 {
print(names[i])
} // Anna Alex Brian Jack
let range = 1...3
for i in range {
print(names[i])
}
let a = 1
var b = 2
for i in a...b {
print(names[i])
}
for i in a...3 {
print(names[i])
}
// 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] {
prin(name)
} // Anna Alex Brian
for name in names[..<2] {
prin(name)
} // Anna Alex
区间类型
let range1: ClosedRange<Int> = 1...3
let range2: Range<Int> = 1..<3
let range3: PartialRangeThrough<Int> = ...5
带间隔的区间值
let hours = 11
let hourInterval = 2
for tickMark in stride(from: 4, through: hours, by: hourInterval) {
print(tickMark)
} // 4 6 8 10
switch
var number = 1
switch number {
case 1:
break
case 2:
break
default:
break
}
case后面必须有语句,否则报错。break可以不写,默认不穿透。如果需要穿透可以使用关键字“fallthrough”
var number = 1
switch number {
case 1:
fallthrough
case 2:
print("number is 2")
default:
print("number is other")
}
// number is 1
// number is 2
switch注意点
- swith必须要保证能够处理所有情况
- case、default后面至少要有一条语句
- 如果不想做任何事,加个break即可
- 如果能保证已经处理了所有情况也可以不用default
复合条件
- switch也支持Character、String类型
let string = "Jack"
switch string {
case "Jack":
fallthrough
case "Rose":
print("Right person")
default:
break
}
使用复合条件代替fallthrough
let string = "Jack"
switch character {
case "Jack", "Rose":
print("Right person")
default:
break
} // Right person
区间匹配、元组匹配
let count = 62
switch count {
case 0:
print("none")
case 1..<5:
print("a few")
case 5..<12:
print("several")
case 12..<100:
print("dozens of")
default:
print("...")
}
let point = (1, 1)
switch point {
case (0, 0):
print("the origin")
case (_, 0): // 前一个值无所谓,依据后一个值判断
print("on the x-axis")
case (-2...2, -2...2):
print("inside the box")
}
值绑定
可以获取到元组中的值,用let或者中var来接收
let point = (2, 0)
switch point {
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))")
} // on the x-axis with an x value of 2
where
接受条件判断
let point = (1, -1)
switch point {
case let (x, y) where x == y:
print("x == y")
case let (x, y) where x == -y:
print("x == -y")
case let (x, y):
print("\(x), \(y) is just some arbitrary point")
}