Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#열거형 Enumertaion #5

Open
yoogail105 opened this issue Oct 9, 2021 · 0 comments
Open

#열거형 Enumertaion #5

yoogail105 opened this issue Oct 9, 2021 · 0 comments

Comments

@yoogail105
Copy link
Owner

#열거형 Enumertaion

1. 열거형이란?

  1. 무작위로 값이 입력되는 것 방지 → 입력값의 오류 발생 가능성 줄인다.

    코드의 안정성 향상

  2. 문자열, 정수값 등 정보를 입력 X선택 O

  3. 연관된 데이터가 멤버로 구성되어 있는 자료형 객체

2. 자료형과의 차이점

  1. 열거형이 가지고 있는 멤버 → 삭제 or 변경 불가

    (구문 자체를 수정하지 않는 이상 불가능)

    but. 배열, 집합, 딕셔너리 등 → 삭제 or 변경 가능

  2. 열거형의 멤버들: 정의되는 시점컴파일러가 미리 인지 가능

    컴파일 시점에 오류를 인지버그 수정 용이

    but. 집단자료형에서 오류 → 런타임 시점에 오류를 인지

3. 열거형의 필요성

  1. 원하지 않는 값이 잘못 입력되는 것을 막고 싶을 때
  2. 입력받을 값을 미리 특정할 수 있을 때
  3. 제한된 값 중에서만 선택할 수 있도록 강제하고 싶을 때

4. 열거형의 사용

enum 열거형이름 {
	case 멤버1
	case 멤버2
	...
}

// 쉼표로 나타낼수도 있다.

enum 열거형이름 { case 멤버1, 멤버2, ...
}

*예시

5. Switch 구문과 열거형

userRecentPurchase를 AppleDevice 열거형을 사용한다고 하면, 초기화 할 때 목록이 뜬다.
Untitled 1

최근에 구매한 애플 디바이스 예제

import UIKit

enum AppleDevice {
    case iPad, iPhone, airPods, mac, watch
}

class PurchaseHistoryViewController: UIViewController {
    
    @IBOutlet var resultLabel: UILabel!
    
    var userRecentPurchase: AppleDevice = .iPad
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 최근구매: 아이폰
        userRecentPurchase = .iPad
    }
    
    @IBAction func checkRecentPurchaseHistory(_sender: UIButton) {
        
        if userRecentPurchase == .iPad {
            resultLabel.text = "당신은 최근에 아이패드를 구매했습니다."
        } else if userRecentPurchase == .iPhone {
            resultLabel.text = "당신은 최근에 아이폰을 구매했습니다."
        } else if userRecentPurchase == .airPods {
            resultLabel.text = "당신은 최근에 에어팟을 구매했습니다."
        } else if userRecentPurchase == .mac {
            resultLabel.text = "당신은 최근에 맥을 구매했습니다."
        } else if userRecentPurchase == .watch {
            resultLabel.text = "당신은 최근에 애플워치를 구매했습니다."
        }
    }

}

→ switch 구문을 활용하기

@IBAction func checkRecentPurchaseHistory(_sender: UIButton) {
        
        switch userRecentPurchase {
        case .iPhone:
            resultLabel.text = "당신은 최근에 아이패드를 구매했습니다."
        case .iPad:
            resultLabel.text = "당신은 최근에 아이폰을 구매했습니다."
        case . airPods:
            resultLabel.text = "당신은 최근에 에어팟을 구매했습니다."
        case .mac:
            resultLabel.text = "당신은 최근에 맥을 구매했습니다."
        case .watch:
            resultLabel.text = "당신은 최근에 애플워치를 구매했습니다."
        }
}

6. 원시값 RawValue

  1. 멤버와 값의 분리

: 숫자 정보, 문자열 정보의 전달이 필요한 경우

: 데이터만으로 의미 전달이 어려울 때 사용

case: 그 자체로 독립적인 값

but. 내부에 또 다른 독립적인 값을 저장할 수 있다.

주의사항

Untitled 1

Enum case cannot have a raw value if the enum does not have a raw type

: 열거형 케이스의 원시값을 설정하기 위해서는, 원시값의 타입을 지정해 주어야 한다.

num AppleDevice: String {
    case iPad = "아이패드"
    case iPhone = "아이폰"
    case airPods = "에어팟"
    case mac = "맥북"
    case watch = "애플워치"
}

프린트할 열거형의 rawValue를 담을 공간을 만들어서 코드를 줄일 수 있다.

@IBAction func checkRecentPurchaseHistory(_sender: UIButton) {
        
        let product = userRecentPurchase.rawValue
        resultLabel.text = "당신은 최근에 \(product)를 구입했습니다."
}
  1. 일부 항목만 원시값을 주는 경우

    1. 문자열 형식의 원시값 지정 → 원래 이름을 원시값으로 가진다.
    enum AppleDevice: String {
        case iPad = "아이패드"
        case iPhone = "아이폰"
        case airPods
        case mac
        case watch
    }

    b. 정수형 형식의 원시값을 지정하면? → 선언이 된 마지막 항목을 기준으로 0부터 1씩 늘어난 값을 차례로.

    enum AppleDevice: Int {
        case iPad = 67
        case iPhone = 90
        case airPods
        case mac
        case watch
    }

Untitled 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant