[swift] 열거형의 연산 및 메서드 정의하기

아래는 Swift 열거형에서의 연산과 메서드 정의에 대한 예시입니다.

연산 정의하기

enum Operation {
    case addition(Int, Int)
    case subtraction(Int, Int)
    case multiplication(Int, Int)
    case division(Int, Int)
    
    func performOperation() -> Int {
        switch self {
        case .addition(let a, let b):
            return a + b
        case .subtraction(let a, let b):
            return a - b
        case .multiplication(let a, let b):
            return a * b
        case .division(let a, let b):
            guard b != 0 else {
                fatalError("Cannot divide by zero")
            }
            return a / b
        }
    }
}

let addition = Operation.addition(5, 3)
let result = addition.performOperation() // 결과: 8

메서드 정의하기

enum TrafficLight {
    case red
    case yellow
    case green
    
    mutating func nextLight() {
        switch self {
        case .red:
            self = .green
        case .yellow:
            self = .red
        case .green:
            self = .yellow
        }
    }
}

var currentLight = TrafficLight.red
currentLight.nextLight() // 현재 신호등 상태: green

이렇게하여 열거형을 사용하여 연산 및 메서드를 정의할 수 있습니다. 이러한 기능은 코드를 구조화하고 표현력을 향상시키는 데 도움이 됩니다.