# 11. Enum이늄 [자바/스위프트]

msi753·2021년 5월 9일
0

🦅 스위프트 문법

목록 보기
7/18
  • enum 정의하는 방법
  • enum이 제공하는 메소드 (values()와 valueOf())
  • java.lang.Enum
  • EnumSet
  • ordinal이란?
  • 타입 세이프티(enum을 사용하는 이유)

자바

enum

묵시적으로 private으로 선언되어 있다

values와 valueOf

ordinal이란?

ordinal은 순서를 리턴하는데
데이터의 순서가 바뀌면 오류발생할 수 있어서 (권장하지 않는다)
@Enumerated(EnumType.STRING) 이름으로 매핑해준다.

enum은 java.lang.Enum을 상속받은 상태이다.

❤️enum 꿀팁

1, 2, 3 이 아니라 10, 20, 30으로 처음 값을 설정해 중간에 값을 넣기 편하도록 한다.

EnumSet

HashSet -> EnumSet으로 변경하기


스위프트

항목순회

CaseIterable 프로토콜

enum School: CaseIterable {
    case primary
    case elementary
    case middle
    case high
    case college
    case university
    case graduate
}

let allCases: [School] = School.allCases
print(allCases) 
//[primary, elementary, middle, high, college, university, graduate]
//원시값이 있을 때는 원시값의 타입 뒤에 쉼표를 쓰고 CaseIterable 채택
enum School: String, CaseIterable {
    case primary = "유치원"
enum School: String, CaseIterable {
    case primary = "유치원"
    case elementary = "초등학교"
    case middle = "중학교"
    case high = "고등학교"
    case college = "대학"
    case unuversity = "대학교"
    @available(iOS, obsoleted: 12.0)
    case graduate = "대학원"
    
    static var allCases: [School] {
        let all: [School] = [.primary,
                             .elementary,
                             .middle,
                             .high,
                             .college,
                             .unuversity]
        #if os(iOS)
        return all
        #else
        return all + [.graduate]
        #endif
    }
}

let allCases: [School] = School.allCases
print(allCases) //실행환경에 따라 다른 결과

연관 값을 갖는 항목순회

연관 값을 갖는: case pasta(taste: PastaTaste)

enum PastaTaste: CaseIterable {
    case cream, tomato
}

enum PizzaDough: CaseIterable {
    case cheeseCrust, thin, original
}

enum PizzaTopping: CaseIterable {
    case pepperoni, cheese, bacon
}

enum MainDish : CaseIterable {
    case pasta(taste: PastaTaste)
    case pizza(dough: PizzaDough, topping: PizzaTopping)
    case chicken(withSauce: Bool)
    case rice
    
    static var allCases: [MainDish] {
        return PastaTaste.allCases.map(MainDish.pasta) + PizzaDough.allCases.reduce([]) { result, dough in
            result + PizzaTopping.allCases.map { topping in
                MainDish.pizza(dough: dough, topping: topping)}
        }
        + [true, false].map(MainDish.chicken)
        + [MainDish.rice]
    }
}

print(MainDish.allCases.count)  //14
print(MainDish.allCases)

순환 열거형 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 final = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))

func evaluate(_ expression: ArithmeticExpression) -> Int {
    switch expression {
    case .number(let value):
        return value
    case .addition(let left, let right):
        return evaluate(left) + evaluate(right)
    case .multiplication(let left, let right):
        return evaluate(left) * evaluate(right)
    }
}

let result: Int = evaluate(final)
print(result)   //18

비교 가능한 열거형 Comparable

<, <=, >=, > 같은 관계형 연산자를 통해 연산이 가능한 타입
sort()도 사용가능하다

enum Condition: Comparable {
    case terrible
    case bad
    case good
    case great
}

let myCondition: Condition = Condition.great
let yourCondition: Condition = .bad

if myCondition >= yourCondition {
    print("제 상태가 더 좋아요")
} else {
    print("당신의 상태가 더 좋아요")
}

switch 구문

enum School {
    case primary, elementary, middle, high, college, university, graduate
}

let 최종학력: School = School.graduate

switch 최종학력 {
case .primary:
    print("유치원입니다")
case .elementary:
    print("초등학교입니다")
case .middle:
    print("중학교입니다")
case .high:
    print("고등학교입니다")
case .college, .university:
    print("대학입니다")
case .graduate:
    print("대학원입니다")
}

// 대학원입니다
profile
👶 Back-End Developer -> 👩‍💻 iOS Developer

0개의 댓글