[swift] 06. 열거형

타입 추론

형을 알 수 있는 경우 생략 가능

enum CompassPoint {
    case north
    case south
    case east
    case west
}


var directionToHead = CompassPoint.west
directionToHead = .east // CompassPoint 라는 것을 알기 때문에 생략 가능

Associated value

열거형의 각 case에 custom type의 추가적인 정보를 저장할 수 있다.

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}


var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
switch productBarcode {
// let 을 전부 사용하면 case let .upc(numberSystem, manufacturer, product, check): 으로 선언 가능
case .upc(let numberSystem, let manufacturer, let product, let check): 
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
    print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."