Swift
Swift - switch-case문
leebean
2021. 10. 4. 17:36
(인덕대학교 컴퓨터소프트웨어학과 iOS프로그래밍기초(21-2학기)한성현 교수님 강의 내용을 변형 및 요약 했습니다.)
switch-case문
- switch-case문 대신에 if~else문을 사용하여 기능은 구현되지만 switch-case문 을 사용하면 코드가 간결해집니다.
- 각 case문 마지막에는 break가 자동으로 들어있습니다.
- switch-case문을 사용한다면 case부분의 내용이 비어 있으면 에러가 납니다.
- switch-case문에 조건을 다 만들었다면 반드시 default를 작성해야 합니다.
- Swift에서는 case에 범위를 지정할 수 있는데 "case[시작]...[끝]" 형식으로 지정이 가능합니다.
(switch-case문 Int형 예시)
var math = 3
switch math{
case 0:
print("00")
case 1:
print("01")
case 2:
print("02")
case 3:
print("03")
default:
print("04 이상 입니다.")
} // math변수가 3이기 때문에 case 3 내용이 출력됩니다.
(switch-case문 Character형 예시)
let startCharacter: Character = "z"
switch startCharacter {
case "a":
print("first alphabet")
case "z":
print("last alphabet")
default:
print("other character")
}// “last alphabet“이 출력 됩니다.
(switch-case문 범위조건 예시)
let op1 = 300
let count : String
switch op1 {
case 0...9:
count = "one dight"
case 10...99:
count = "two dight"
case 100...999:
count = "three dight"
default:
count = "four more dights"
}
print("\(count) 입니다.")
// op1의 변수가 세 자리 수이기 때문에 ”three dight 입니다.“ 가 출력됩니다.