2024-04-08 约 800 字 预计阅读 2 分钟
条件控制
if-else
区别
if后面的条件的小括号可以省略
1
2
3
4
5
if age > 22 {
print ( "age > 22" )
} else {
print ( "age <= 22" )
}
while
1
2
3
4
5
6
7
8
9
var n = 10
while n > 0 {
print ( "n == \( n ) " )
n -= 1
}
repeat-while
相当于do-while
1
2
3
4
5
6
7
repeat {
print ( "n == \( n ) " )
n -= 1
} while ( n > 0 )
for
闭区间运算符 a…b a<= 值 <=b
半开区间运算符 a..< b a<= 值 < b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
闭区间运算符 index >= 0 && index <= 3
123 0
123 1
123 2
123 3
*/
for index in 0. .. 3 {
print ( "123 \( index ) " )
}
/*
半开区间运算符 index >= 0 && index < 3
123 0
123 1
123 2
*/
for index in 0. .< 3 {
print ( "123 \( index ) " )
}
/**
用于数组
123 a
123 j
123 b
123 c
*/
let names = [ "a" , "j" , "b" , "c" ]
for name in names [ 0. .. 3 ] {
print ( "123 \( name ) " )
}
单侧区间 让区间朝一个方向尽可能远
names[0...] 代表取值从0到数组最后一个
names[...2] 代表取值从0到数组下标为2终止
names[..<2] 代表取值从0到数组下标为1终止
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
let names = [ "a" , "j" , "b" , "c" ]
/*
123 a
123 j
123 b
123 c
*/
for name in names [ 0. ..] {
print ( "123 \( name ) " )
}
/*
123 a
123 j
123 b
*/
for name in names [... 2 ] {
print ( "123 \( name ) " )
}
/*
123 a
123 j
*/
for name in names [..< 2 ] {
print ( "123 \( name ) " )
}
区间类型
1
2
let range = "dd" ... "ii"
print ( range )
带间隔的区间值
1
2
3
4
5
6
7
8
9
let hour = 11
let interval = 2
// stride 从4开始 累加2 不超过11
// 4 6 8 10
for index in stride ( from : 4 , through : hour , by : interval ){
print ( index )
}
switch
case、default 后面不能写大括号{}
默认可以不写break 并不会贯穿条件
需要贯穿条件 可以使用fallthrough也可以用,分开
switch必须要保证能处理所有情况
case、default 后面至少要有一条语句,如果不想处理任何事情可以加break
switch也支持Character、String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
switch age {
case 1 :
fallthrough
case 2 :
print ( "1 2" )
default :
print ( "other" )
}
switch age {
case 1 , 2 :
print ( "1 2" )
default :
print ( "other" )
}
let name = "jack"
switch name {
case "jack" :
print ( "this is jack" )
default :
print ( "this is other" )
}
where
1
2
3
4
5
6
7
let numbers = [ 1 , - 10 , 2 , 5 , - 6 , 89 ]
for item in numbers where item > 0 {
print ( "只输出大于0的 \( item ) " )
}