dev._.note

[Swift] Enum 열거형 본문

Dev/SWIFT

[Swift] Enum 열거형

Laena 2024. 2. 23. 21:46

📌 Enum(열거형)

  • Enum은 관련된 값으로 이뤄진 그룹을 같은 타입으로 선언해 타입 안전성(type-safety)을 보장하는 방법으로 코드를 다룰 수 있음.
  • 값 타입
// 간단한 열거형 선언
enum CompassDirection {
    case north
    case south
    case east
    case west
}

// 열거형의 인스턴스 생성 및 사용
var direction = CompassDirection.north
var anotherDirection = direction // 값 복사

direction = .east // 값을 변경해도 anotherDirection에는 영향이 없음

print(direction) // 출력: east
print(anotherDirection) // 출력: north
  • Swift의 열거형(Enum)은 연관 값(Associated Values)을 가질 수 있음. 이는 각 case가 특정 값을 연결하여 저장할 수 있는 기능을 제공.
// 연관 값을 가진 열거형 선언
enum Trade {
    case buy(stock: String, amount: Int)
    case sell(stock: String, amount: Int)
    case hold
}

// 열거형의 인스턴스 생성 및 사용
let trade1 = Trade.buy(stock: "AAPL", amount: 100)
let trade2 = Trade.sell(stock: "GOOG", amount: 50)
let trade3 = Trade.hold

// switch 문을 사용하여 연관 값 추출
func processTrade(trade: Trade) {
    switch trade {
    case .buy(let stock, let amount):
        print("Buy \(amount) shares of \(stock).")
    case .sell(let stock, let amount):
        print("Sell \(amount) shares of \(stock).")
    case .hold:
        print("Hold this position.")
    }
}

// 각 열거형 케이스에 따라 다른 동작 수행
processTrade(trade: trade1) // 출력: Buy 100 shares of AAPL.
processTrade(trade: trade2) // 출력: Sell 50 shares of GOOG.
processTrade(trade: trade3) // 출력: Hold this position.
enum CompassPoint {
    case north
    case south
    case east
    case west
}

// 한 케이스 선언 방법
var directionToHead = CompassPoint.west
directionToHead = .east

// 활용 예시 1
directionToHead = .south
switch directionToHead {
case .north:
    print("북쪽")
case .south:
    print("남쪽")
case .east:
    print("동쪽")
case .west:
    print("서쪽")
}
// 출력값: "남쪽"

// allCases 
enum Beverage: CaseIterable {
    case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) 잔 주문 가능합니다.")
// 출력값: 3잔 주문 가능합니다
// 실제 Optional의 정의
@frozen public enum Optional<Wrapped> : ExpressibleByNilLiteral {

    /// The absence of a value.
    ///
    /// In code, the absence of a value is typically written using the `nil`
    /// literal rather than the explicit `.none` enumeration case.
    case none

    /// The presence of a value, stored as `Wrapped`.
    case some(Wrapped)


print(Optional.none == nil) // true

 

Class, Struck, Enum의 차이점

  • 붕어빵 만드는 기계를 클래스(class), 붕어빵을 그 기계로 만들어진 실제 객체(object)로 비유할 수 있음.
  • 객체는 클래스를 실체화한 것, 프로그래밍에서는 메모리에 올라가는 인스턴스가 된 것.
  • 객체는 클래스의 인스턴스로 자신만의 속성(프로퍼티)과 행위(메서드)를 가짐.

참고 자료: The Swift Programming Language - Enumerations

https://bbiguduk.gitbook.io/swift/language-guide-1/enumerations