// 7원시값으로 italy 식별 가능 let possibleCountry = Country(rawValue: 7) // italy
// 99의 위치로 나라를 찾는다면 원시값 초기화로부터 반환된 옵셔널 Country값은 nil임 // 99의 원시값으로 나라를 찾기위해 옵셔널 바인딩 사용 // if let someCountry = Country(rawValue: countryToFind) 구문은 옵셔널 Country를 생성 // 옵셔널 Country의 값을 someCountry 에 설정함 // 근데 99의 위치에 행성값이 없으니까 else구문이 실행됨 let countryToFind = 99 if let someCountry = Country(rawValue: countryToFind) { switch someCountry { case .korea: print("Amazing place to live with lots of good services") default: print("Nice to visit") } } else { print("There is no decent place to live at position \(countryToFind).") } // There is no decent place to live at position 99.
5) 열거형의 메서드 활용
func 키워드를 사용하여 열거형에서 메서드 활용 가능
enum Day { case mon, tue case wed, thur case fri case sat, sun
func sendMessage() { switch self { case .mon, .tue: print("버텨..") case .wed, .thur: print("좀만 더 버텨..") case .fri: print("존버는 승리한다..") case .sat, .sun: print("무야호오우오오오오옹") } } }
enum ArithmeticExpression { case number(Int) indirect case subtract(ArithmeticExpression, ArithmeticExpression) indirect case divide(ArithmeticExpression, ArithmeticExpression) }
indirect enum ArithmeticExpression2 { case number(Int) case subtract(ArithmeticExpression, ArithmeticExpression) case divide(ArithmeticExpression, ArithmeticExpression) } 두 열거형을 코딩했을때는 오류가 발생했고, 두번째 열거형에 ArithmeticExpression에 2를 붙였더니 오류가 사라짐
let eighty = ArithmeticExpression.number(80) let thirty = ArithmeticExpression.number(30) let subtract = ArithmeticExpression.subtract(eighty, thirty) let result = ArithmeticExpression.divide(subtract, ArithmeticExpression.number(10))
func calculate(_ expression: ArithmeticExpression) -> Int { switch expression { case let .number(value): return value case let .subtract(left, right): return calculate(left) - calculate(right) case let .divide(left, right): return calculate(left) / calculate(right) } }