모바일앱/Swift

플로우컨트롤. (조건문) Switch

GeekCode 2021. 9. 29. 23:46
반응형

조건문은 

if - else 구문과 Switch 구문이 있다.

 

Switch

확인하려는 변수를 스위치 앞에 두고

가능한 케이스를 체크하고 부합하면 해당하는 코드를 실행시키는 형식이다.

위에서 아래로 순서대로 체크

 

switch문에 int 타입 사용할 때

// ---Switch

let num = 10

switch num {
case 0:
    print("---> 0 입니다.")
case 10:
    print("---> 10 입니다.")
default:
    print("---> 나머지 입니다.")
}

/*
--> default 값이 없으면 숫자가 너무 많다는 에러
error: Practice.playground:5:1: error: switch must be exhaustive
switch num {
^

Practice.playground:5:1: note: do you want to add a default clause?
switch num {
^
*/


let num = 10

switch num {
case 0:
    print("---> 0 입니다.")
case 0...10:
    print("---> 0부터 10 사이 입니다.") // 중간에 레인지를 넣어서 표현 가능
case 10:
    print("---> 10 입니다.")
default:
    print("---> 나머지 입니다.")
}

//---> 0부터 10 사이 입니다.

 

 

switch문에 string 타입 사용할 때

// ---> String 타입

let pet = "bird"

switch pet {
case "dog","cat": //여러개 조건도 가능
    print("---> 집동물이네요? ")
default:
    print("---> 잘 모르겠습니다 ")

}
//---> 잘 모르겠습니다



switch pet {
case "dog","cat","bird": //여러개 조건도 가능
    print("---> 집동물이네요? ")
default:
    print("---> 잘 모르겠습니다 ")
}

//---> 집동물이네요?

 

Case 안에 where 사용가능

let num = 20
switch num {
case _ where num % 2 == 0 :
    print("---> 짝수")
default:
    print("---> 홀수")

}
// ---> 짝수

let num = 5
switch num {
case _ where num % 2 == 0 :
    print("---> 짝수")
default:
    print("---> 홀수")

}
// ---> 홀수
반응형