열거형(Enumeration)

린다·2022년 2월 17일
0

The Swift Language Guide

목록 보기
2/7
post-thumbnail

아래의 글은 The swift programming languagebbiguduk님, jusung님의 번역본을 보며 공부한 내용입니다.

정의

  • 관련된 값의 그룹을 위한 타입을 정의
  • type-safe
  • raw value로 주어질 수 있는 값은 문자열, 문자, 정수, 부동소수타입
  • computed property, instance method 모두 구현 가능, 초기화 구문도 정의 가능, 프로토콜 채택도 가능

구문

enum SomeEnumeration {
    // enumeration definition goes here
}
  • case로 새로운 케이스를 나타낼 수 있음
enum CompassPoint {
    case north
    case south
    case east
    case west
}
  • 콤마로 구분하여 한줄로 표기도 가능함
enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
var directionToHead = CompassPoint.west
// 한 번 할당된 후에는 CompassPoint라는 타입 이름 생략 가능
directionToHead = .east

Switch 구문

directionToHead = .south
switch directionToHead {
case .north:
    print("Lots of planets have a north")
case .south:
    print("Watch out for penguins")
case .east:
    print("Where the sun rises")
case .west:
    print("Where the skies are blue")
}
// Prints "Watch out for penguins"
  • switch문을 사용할 때 모든 케이스가 반드시 고려되어야함
  • 모든 케이스에 대해 제공하는 것이 적절하지 않은 경우에는 default로 작성되지 않은 케이스들에 대해서 공통적으로 대처할 수 있음
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
    print("Mostly harmless")
default:
    print("Not a safe place for humans")
}
// Prints "Mostly harmless"

Iterating(케이스 반복)

  • case들에 대해서 반복해야하는 경우, CaseIterable을 작성하면 됨
enum Beverage: CaseIterable {
    case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")
// Prints "3 beverages available"

연관값(Associated Value)

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
  • 연관값을 사용하고 싶은 경우에는 let/var로 정의한 후 case 바디 내에서 사용할 수 있음
switch productBarcode {
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."

// 연관된 값을 모두 사용할 경우에는 케이스 이름 앞에 var, let 붙이면 됨
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
    print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."

원시값(Raw Values)

  • 모든 케이스를 동일한 타입의 기본값으로 미리 채울 수 있음
enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}
  • 문자열, 문자, 또는 어떠한 정수 또는 부동소수점 숫자 타입
  • 유일한 값만 선언 가능함
  • 원시값과 연관된 값의 차이점
    • 원시값은 한 번 선언하면 변함없이 사용가능
    • 연관된값은 새로운 상수나 변수에 케이스를 할당할때마다 달라질 수 있음

암시적으로 할당된 원시값

  • 원시값을 수동으로 할당하지 않으면 swift 내부에서 자동으로 할당함
  • 정수를 사용할 경우, 원시값을 할당하지 않으면 자동으로 이전 케이스의 원시값 + 1씩 자동 할당함
    • 첫번째 케이스에 할당이 돼있지않으면 0 자동할당
  • 문자열을 사용할 경우, 암시적으로 케이스의 이름을 할당함
  • .rawvalue로 원시값에 접근할 수 있음

원시값으로 초기화

  • 원시값을 통해 케이스 혹은 nil을 반환할 수 있음 → 열거형의 새 인스턴스를 만들 수 있음
let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.uranus
  • 하지만 해당 원시값을 갖는 케이스가 존재하지 않을수도 있기 때문에 원시값 초기화는 항상 옵셔널 열거형 케이스를 반환함
let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind) {
    switch somePlanet {
    case .earth:
        print("Mostly harmless")
    default:
        print("Not a safe place for humans")
    }
} else {
    print("There isn't a planet at position \(positionToFind)")
}
// Prints "There isn't a planet at position 11"

재귀 열거형(Recursive Enumerations)

  • 열거형 케이스에 하나 이상의 연관된 값으로 열거형의 다른 인스턴스를 가지고 있는 열거형
  • 키워드 indirect
enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
  • case 앞에 Indirect를 붙여서 해당 케이스를 indirect로 생성할 수 있고 아니면 열거형 앞에 붙여서 열거형 자체를 Indirect로 생성할 수도 있음
indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
    case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))

0개의 댓글