Enumeration(열거형)
원시 값이 있는 열거형
- 아래의 경우는 원시 값을 지정해주지 않고, 그냥 Int만 채택해주어도 알아서 원시값이 설정된다.
enum SoccerPlayer: Int {
case attacker = 0
case defenser = 1
case midfielder = 2
}
연관 값이 있는 열거형
- 아래와 같이 default로 존재하는 연관 값을 가진 case, default가 없는 연관 값 case도 존재한다.
enum TypeName {
// default 값을 넣을 수 있다.
case caseName(type: String = "NameString")
case caseNameTwo(typeNumber: Int)
}
- 아래와 같이 switch문으로 연관 값을 처리할 수 있다.
let typeName: TypeName = .caseNameTwo(typeNumber: 2)
switch typeName {
case .caseName:
print("")
case .caseNameTwo(typeNumber: 3):
print("")
case .caseNameTwo:
print("")
default:
print("")
}
연산 프로퍼티 사용하기
enum BankingService: CaseIterable, Equatable {
static var allCases: [BankingService] = [deposit(), loan()]
case deposit(Int = 0)
case loan(Int = 0)
var title: String {
switch self {
case .deposit: return "예금"
case .loan: return "적금"
}
}
CaseIterable
A type that provides a collection of all of its values
- 열거형의 값들을 배열 컬렉션과 같이 순회할 수 있도록 해주는 프로토콜이다!
for-in loop
,forEach
,allCases
를 활용할 수 있다.
Equatable
A type that can be compared for value equality.
- 등호연산자(=), 같지 않음 연산자(≠)를 사용하여 동등성을 비교할 수 있다.
- 클래스, 구조체, enum 등이 채택이 가능하다.
연관값
enum AppleDevice {
case iPhone(model: String, storage: Int) // named tuple
case iMac(size: Int, model: String, price: Int)
case macBook(String, Int, Int) // unnamed tuple
}
var gift = AppleDevice.iPhone(model: "X", storage: 256)
switch gift {
case .iPhone(model: "X", storage: 256):
print("iPhone X and 256GB")
case .iPhone(model: "X", _)
// 와일드카드 패턴 사용 가능
print("iPhone X")
case .iPhone:
// 연관값 생략 가능
print("iPhone")
case .iPhone(let model, let storage):
// 블록 내부에서 연관값을 사용할 땐 상수로 바인딩
// 값을 변경할 때는 var 로 변경가능
print("iPhone \(model) and \(storage)GB")
case let .iMac(size, model, price):
// 모든 연관값을 동일한 형태로 바인딩한다면
// let 키워드를 열거형 케이스 앞에 표기하는 것도 가능
print("iMac \(size), \(model), \(price)")
}
static let의 활용(상수)
final class ProfileViewController: UIViewController {
private enum Metric {
static let profileImageViewLeft = 10.f
static let profileImageViewRight = 10.f
static let nameLabelTopBottom = 8.f
static let bioLabelTop = 6.f
}
private enum Font {
static let nameLabel = UIFont.boldSystemFont(ofSize: 14)
static let bioLabel = UIFont.boldSystemFont(ofSize: 12)
}
private enum Color {
static let nameLabelText = 0x000000.color
static let bioLabelText = 0x333333.color ~ 70%
}
}
'Swift' 카테고리의 다른 글
[Swift] initializers(생성자) (0) | 2023.03.17 |
---|---|
[Swift] Closure (0) | 2023.03.09 |
[Swift] mutating (0) | 2023.02.24 |
[Swift] 값 타입, 참조 타입, let, var (0) | 2023.02.24 |
[Swift] 함수 return에대한 고민 (0) | 2023.02.20 |