5. 元组
1. if-else
- if 后面的条件只能是Bool类型, if 后面括号可以省略
var age : Int = 30
if age == 30 {
print("my age is \(age)")
}
2. while
- while 后面需要时 bool 类型
- repeat-while 等同于 do-while
var count = 0
while count<=5 {
print("num is \(count)")
count += 1
}
count = 0
repeat {
print("num is \(count)")
}while count>0
3. for-in
区间运算
- 闭区间运算符:a...b ,表示 a<= 取值 <=b
- 半开区间运算符:a..<b, a <= 取值 < b
- 单侧区间:让区间朝一个方向尽可能的远 a..., a 到无限大
// 区间类型
let rang1: ClosedRange<Int> = 1...3
let rang2: Range<Int> = 1..<3
let rang3: PartialRangeThrough<Int> = ...3
for-in常见写法
// 方式一: 默认num是let 类型,可以省略不写
for num in 1...10{
print(num)
}
// 方式二: 如果要修改 num 的值,需要更改为变量
for var num in 1...10 {
num += 100
print(num)
}
// 方式三: 去过不需要用到 num 可以使用_缺省
for _ in 1...10 {
print("hello,world")
}
- 区间运算符应用
// 设置数组的取值范围
let arr2 = ["my", "name", "is", "Alex"]
for str in arr2[1...2] {
print(str)
}
// 单侧区间运算符
for str in arr2[2...] {
print(str)
}
- 带间隔的区间值, 使用 stride来进行间隔设置
// num 的取值:从50开始,累加10,不超过100
let number = 10
for num in stride(from: 50, to: 100, by: number) {
print(num)
}
4. Switch
switch 与普通 switch 使用类似
注意点:
- case、default后面不能写大括号{}
- 使用fallthrough可以实现贯穿效果
- switch必须要保证能处理所有情况
- case、default后面至少要有一条语句 ;如果不想做任何事,加个break即可
- 如果能保证已处理所有情况,也可以不必使用default
- switch也支持Character、String类型
enum Answer { case right, wrong }
let answer = Answer.right
switch answer {
case .right:
print("right")
case .wrong:
print("wrong")
}
- 复合条件
let name = "chuan"
switch name {
// 使用, 分割,可以同时判断多个条件,满足一个即执行
case "chuan", "bing":
print("chuan/bing")
default:
break
}
- 区间匹配、元组匹配
// 区间匹配
let count_num = 99
switch count_num {
case 1...10:
print("1...10")
case 11...20:
print("11...20")
case 21..<30:
print("21..<30")
case 30...:
print(count_num)
default:
break
}
// 元组匹配
let point = (1, 1)
switch point {
case (0, 0):
print("the origin")
case (_, 0):
print("on the x-axis")
case (0, _):
print("on the y-axis")
case (-2...2, -2...2):
print("inside the box")
default:
print("outside of the box")
}
- 值绑定,如果有一个值相同,另外一个则会进行绑定
// 值绑定
let point1 = (1, 1)
switch point1 {
case (let x, 0):
print("the origin is\(x)")
case (let x, let y):
print("x is \(x), y is \(y)")
case let (x, y):
print("xxxx is \(x), yyyy is \(y)")
default:
print("outside of the box")
}
5. where
where用于判断某个条件满足才会进行执行
// for
for num in 1...100 where num % 10 == 0 {
print(num)
}
// switch
let point2 = (1, 2)
switch point2 {
case let (x, y) where x == y:
print("x is \(x) y is \(y)")
case let (x, y) where x != y:
print("xx is \(x) yy is \(y)")
default:
break
}
网友评论