본문 바로가기

Swift

[Swift] 조건문(Conditional Statement - if / switch)

728x90

if Statement

  • 특정 조건에서 코드를 실행하거나 실행하지 말아야하는 상황에 사용
  • swift에서 if 구문은 조건의 값이 꼭 Bool 타입이어야 합니다.
  • 조건을 소괄호로 묶을 필요가 없습니다.
let first: Int = 5
let second: Int = 7

if first > second {
    print("first > second")
} else if first < second {
    print("first < second")
} else {
    print("first == second")
}

Switch Statement

  • switch 구문의 조건을 소괄호로 묶을 필요가 없습니다.
  • case 내의 모든 코드를 실행하면 break가 없어도 switch 구문이 종료됩니다.
  • switch 구문의 case를 연속 실행하려면 fallthrough 키워드를 명시해주어야 합니다.
  • switch의 조건에 다양한 값이 들어갈 수 있습니다.
  • 비교될 값이 한정적이지 않다면 default case를 꼭 작성해야 합니다.
  1. 기본 Switch 문
// 기본적인 Switch 예제
let number: Int = 5

switch number {
case 0:
    print("is 0")
case 1...10:
    print("between 1 and 10")
default:
    print("number < 0 or number > 10")
}
  1. 문자열과 사용해보기
// 문자열, 튜플, 열거형 등 다양한 값의 사용이 가능합니다.
let name: String = "Sophie"

switch name {
case "Sophie" :
    print("Hello Sophie!")
case "Sandy" :
    print("Hello Sandy!")
case "Lina":
    print("Hello Lina!")
default:
    print("\\(name) ????!?!?!")
}

// 이렇게도 쓸 수 있어요.
switch name {
case "Sophie", "Sandy", "Lina" :
    print("Hello \\(name)!")
default:
    print("\\(name) ????!?!?!")
}

// 이렇게도 쓸 수 있어요. #2
switch name {
case "Sophie":
    fallthrough
case "Sandy":
    fallthrough
case "Lina":
    print("Hello \\(name)!")
default:
    print("\\(name) ????!?!?!")
}
  1. 튜플과 사용해보기
// 튜플에 사용해보기
let sophieInfo: (name: String, age: Int) = ("Sophie", 27)

switch sophieInfo {
case ("Sophie", 27) :
    print("정확해요")
case ("Sophie", _) :
    print("이름만 맞췄어요. 나이는 \\(sophieInfo.age)입니다.")
case (_, 27):
    print("나이만 맞췄어요. 이름은 \\(sophieInfo.name)입니다.")
default:
    print("?????")
}

// 튜플 값 바인딩해보기
// 위의 switch 문을 이렇게도 써볼 수 있어요.
switch sophieInfo {
case ("Sophie", 27) :
    print("정확해요")
case ("Sophie", let age) :
    print("이름만 맞췄어요. 나이는 \\(age)입니다.")
case (let name, 27):
    print("나이만 맞췄어요. 이름은 \\(name)입니다.")
default:
    print("?????")
}
  1. where 절 사용해보기
    1. case의 조건을 좀더 확장해서 사용할 수 있습니다.
// where 절 사용해보기
// switch case에 조건을 추가하고 싶을 때 유용해요
let dish: String = "Pasta"
let sauce: String = "Tomato"

switch dish {
case "Pasta":
    if sauce == "Tomato" {
        print("토마토 파스타")
    } else if sauce == "Cream" {
        print("크림 파스타")
    }
default:
    break
}

// 이렇게 쓸 수 있어요.
switch dish {
case "Pasta" where sauce == "Tomato":
    print("토마토 파스타")
case "Pasta" where sauce == "Cream":
    print("크림 파스타")
default:
    break
}
  1. 열거형과 사용해보기
    1. 한정된 범위의 값을 case로 사용하고, 각 케이스를 모두 구현한 경우 default가 필요 없어요.
      enum Weekdays {
          case monday
          case tuesday
          case wednesday
          case thurseday
          case friday
          case saturday, sunday
      }
      
      let today: Weekdays = .saturday
      switch today {
      case .monday, .tuesday, .wednesday, .thurseday, .friday:
          print("아직 평일")
      case .saturday, .sunday:
          print("드디어 주말!")
      }
      
      // 이렇게도 쓸 수 있어요 1
      switch today {
      case .saturday, .sunday:
          print("드디어 주말!")
      default:
          print("아직 평일")
      }
      
      // 이렇게도 쓸 수 있어요 2
      switch today {
      case .saturday, .sunday:
          print("드디어 주말!")
      case _:
          print("아직 평일")
      }
      
      // 만약 열거형에 타입이 추가된 경우, switch 구문에서 모든 타입 case가 정의되지 않았을 것이므로 컴파일 에러가 발생하므로, 이를 방지하기 위해 @unknown 속성을 사용할 수 있어요.
      enum Dish {
          case Pasta
          case Pizza
          case Steak // 이게 추가됐다면,
      }
      
      let myDish: Dish = .Pizza
      switch myDish {
      case .Pasta:
          print("I ordered Pasta")
      case .Pizza:
          print("I ordered Pizza")
          
      @unknown case _:
          print("New Menu?")
      }
      ​

 

728x90

'Swift' 카테고리의 다른 글

[Swift] 함수(Function)  (0) 2023.11.15
[Swift] 반복문 (Loop - for / while / repeat-while)  (0) 2023.11.15
[Swift] 연산자  (0) 2023.11.08
[Swift] 변수와 상수  (0) 2023.11.07
[Swift] Swift 언어적 특징  (0) 2023.11.06