https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID134
swift 공식문서에서 switch where 키워드 관련 부분
swift의 switch 문에서는 아래처럼 case에 tuple을 사용할 수도 있고 변수에 튜플 값을 바인딩 할 수도 있고(x, y에 튜플 값이 하나씩 들어감) where 키워드를 사용하여 case 안에서 또 다른 조건을 추가할 수 있다.
// 출처: https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID134
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let(x,y) where x == y:
print("x: \(x) y: \(y)")
case let(x,y) where x == -y:
print("x: \(x) y: \(y)")
default:
fatalError("Unsupported")
}
if문으로 한다면 이렇게도 할 수 있는데 비교해야 하는 경우의 수가 얼마나 많으냐에 따라 switch 또는 if 문을 선택해서 사용하면 될 듯 하다.
let (a, b) = (1, -1)
if a == b {
print("a is equal to b")
} else {
print("not equal")
}
https://what-whale-wants-to-say-is.tistory.com/60
[swift] switch vs. if 언제 쓸까? (짧음 주의)
비교해야 하는 조건이 5개를 넘으면 switch, 5개 이하면 if .....^^ if conditions > 5 { useSwitch() else { useIf() }
what-whale-wants-to-say-is.tistory.com
반응형
'swift & iOS > swift' 카테고리의 다른 글
[swift] 함수에 여러 개의 argument 넣기(...) (0) | 2022.01.16 |
---|---|
[swift] guard...else... (0) | 2022.01.16 |
[Swift] 정수 나누기 (9 나누기 10을 했는데 0이 나오다) (0) | 2022.01.14 |
[swift] 연산자들 (==, ..., ??) (0) | 2022.01.10 |
[swift] 타입 체크 (is) (0) | 2022.01.10 |