Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- Xcode
- RxCocoa
- map
- 애니메이션
- Observable
- tableView
- Protocol
- UICollectionView
- combine
- HIG
- ios
- UITextView
- 리팩토링
- clean architecture
- uitableview
- uiscrollview
- 리펙토링
- 스위프트
- Human interface guide
- ribs
- rxswift
- SWIFT
- collectionview
- 클린 코드
- Clean Code
- swiftUI
- swift documentation
- Refactoring
- scrollview
- MVVM
Archives
- Today
- Total
김종권의 iOS 앱 개발 알아가기
[iOS - swift] 중첩 case 처리 방법 (#case where) 본문
중첩 case
- 커피를 구분하는 switch-case문이 있을때, associated value에 다른 타입이 있는 경우
enum BeverageType {
case coffee(coffeeType: CoffeeType)
}
enum CoffeeType {
case latte
}
enum OrderInfo {
case specialOrder(customerName: String, drink: BeverageType)
}
let order1: OrderInfo = .specialOrder(customerName: "jake", drink: .coffee(coffeeType: .latte))
- 이것을 사용하는 주문 쪽에서는 타입이 여러개이므로 switch-case에서 아래처럼 여러 단계를 가져갈 수 있음
- OrderInfo안에 BeverageType이 있고, BeverageType안에 CoffeeType이 있으므로 아래처럼 계속 길어지는 형태로 사용
func processOrder(order: OrderInfo) {
switch order {
case let .specialOrder(name, beverageType):
switch beverageType {
case .coffee(let coffeType):
switch coffeType {
case .latte:
print("스페셜 오더 - 고객명: \(name), 음료: 라떼")
}
}
default:
print("기타 주문 처리")
}
}
- 하지만 이렇게 길어지게되면 읽기가 힘들기 때문에 다른 방법으로 표현이 가능
- associated value에 접근할 때, 바로 원하는 타입을 입력해주면 마치 조건문처럼 사용할 수 있음
func processOrder(order: OrderInfo) {
switch order {
case .specialOrder(let name, .coffee(coffeeType: .latte)):
print("스페셜 오더 - 고객명: \(name), 음료: 라떼")
default:
print("기타 주문 처리")
}
}
cf) case where 도 이와 유사하게 사용 가능
- case 맨 뒤에 where를 쓰고 타입을 비교하는 값을 넣는 방법
- 단, 이 방법보단 위 방법이 더욱 간결하므로 associated value가 enum형태이면 위 형태로 사용하고, enum이 아닌 문자열 비교, 숫자 비교 같은 타입들은 where로 쓰기
switch order {
case .specialOrder(let name, .coffee(let coffeeType)) where coffeeType == .latte:
print("스페셜 오더 - 고객명: \(name), 음료: 라떼")
default:
print("기타 주문 처리")
}
'iOS 응용 (swift)' 카테고리의 다른 글
| [iOS - swift] fixedSize(horizontal:vertical:) 개념 (SwiftUI에서 자식 뷰가 그려지는 원리) (7) | 2025.06.04 |
|---|---|
| [iOS - swift] 제네릭과 프로토콜 적절히 사용하는 방법 (프로토콜보다 제네릭이 좋은 점) (0) | 2025.05.28 |
| [iOS - swift] 프로토콜 타입을 사용할 때 자동완성 any 의미 (existential any, existential type) (4) | 2025.04.09 |
| [iOS - swift] deprecated 자동완성 fix 버튼 제공하기 (renamed) (3) | 2025.02.05 |
| [iOS - swift] private extension과 fileprivate extension 개념 (2) | 2025.01.30 |
Comments