스위프트의 switch
스위프트의 switch
If else구문은 제한된 개수의 조건을 검사할 때는 적절한지만 많은 조건을 처리할 때는 부적절할 수 있다 이때 사용 가능한것이 switch구문이다 c언어에서 가져왓지만 스위프트의 switch구문은 몇가지 차이점이 존재한다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let value = 5
switch (value)
{
case 0, 1, 2:
print ("zero or one or two")
case 3:
print ("three")
case 4:
print("four")
case 5:
print("five")
default:
print("out of range")
}//: five를 출력한다
switch 구문 범위 사용하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let value = 43
switch (value)
{
case 0...20:
print ("0~20")
case 21...40:
print ("21~40")
case 41...60:
print("41~60")
case 61...80:
print("61~80")
default:
print("out of range")
}//:41~60 출력
where 구문 사용
where구문은 추가적인 조건을 추가하기 위해서 사용할 수 있다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let value = 38
switch (value)
{
case 0...20 where value % 2 == 0:
print ("0~20 and even")
case 21...40 where value % 2 == 0:
print ("21~40 and even")
case 41...60 where value % 2 == 0:
print("41~60 and even")
case 61...80 where value % 2 == 0:
print("61~80 and even")
default:
print("out of range")
} //:21~40 and even 출력
fallthrough 구문
위 결과를 본다면 다른 언어의 switch와 다르게 해당 case를 만나면 break를 쓰지 않아도 switch구문은 자동으로 빠져나간다 fallthrough를 사용한다면 다은 case구문으로 계속 진행할 수 있다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let value = 38
switch (value)
{
case 0...20 where value % 2 == 0:
print ("0~20 and even")
fallthrough
case 21...40 where value % 2 == 0:
print ("21~40 and even")
fallthrough
case 41...60 where value % 2 == 0:
print("41~60 and even")
fallthrough
case 61...80 where value % 2 == 0:
print("61~80 and even")
fallthrough
default:
print("out of range")
}
출력은 21~40 and even, 41~60 and even, 61~80 and even, out of range 조건에 맞든 안맞든 fallthrough가 있다면 이후 case들은 모두 출력되었다
break
스위프트에서는 자동으로 스위치문을 나가서 크게 필요가 없지만 default구문에서 아무런 작업이 없을 때 break구문을 사용한다
This post is licensed under CC BY 4.0 by the author.