[iOS] Enum, 당신이 몰랐던 \(truth.count)가지 사실

유인호·2024년 1월 24일
0

iOS

목록 보기
23/64

1. Enum은 저장 프로퍼티를 사용하지 못한다.

enum SurpriseEnum {
	let storeProperty = "저장프로퍼티인듯" 
    // Error! Enums must not contain stored properties
    // 인스턴스 저장 프로퍼티는 인스턴스가 생성이 되어야 하는데, 
    // Enum은 인스턴스를 생성하지 못하는 특성이 있음.
}

2. 그러나 타입 저장 프로퍼티는 사용 가능

enum SurpriseEnum {
	static let storeProperty = "타입저장프로퍼티인듯" 
}

3. Int, String 프로토콜을 상속받아 rawValue를 설정할 수 있다.

enum SurpriseEnum: Int {
	case one = 0
	case two = 1
	case three = 2
}

enum SurpriseEnum: String {
	case one = "1"
	case two = "2"
	case three = "3"
}

4. Int의 경우 기본적으로 0부터 시작하게 되어서 이런식으로 활용할 수 있다.

// 자동으로 0,1,2가 들어감
enum SurpriseEnum: Int {
	case one 
	case two 
	case three 
}

// 앞에 rawValue를 설정하면 뒤에는 +1된 값들로 들어간다. 각각 5,6,7
enum SurpriseEnum: Int {
	case one = 5
	case two 
	case three 
}

// 중간에 rawValue를 설정한 경우 각각 0,10,11 이런식으로 들어간다.
enum SurpriseEnum: Int {
	case one 
	case two = 10
	case three 
}

5. String의 경우 rawValue를 따로 설정하지 않을 경우 case 이름 그대로 rawValue가 만들어진다.

// 각각 Hello, two, three
enum SurpriseEnum: String {
	case one = "Hello"
	case two 
	case three 
}

6. CaseIterable을 사용하면 모든 case들이 담긴 배열을 쉽게 만들 수 있다.

enum SurpriseEnum: String, CaseIterable {
	case one
	case two 
	case three 
}

let allCases = SurpriseEnum.allCases // 배열로 만들어줌

7. rawValue는 중복되면 안된다.

enum SurpriseEnum: Int {
	case one = 0
	case two = 0 // Error! Raw value for enum case is not unique
	case three = 0 // Error! Raw value for enum case is not unique
}

8. Enum과 Switch문은 궁합이 잘 맞다.

switch SurpriseEnum.allCases[1] {
	case .one: print("1")
	case .two: print("2")
	case .three: print("3")
}

9. Enum과 Switch문을 사용하다보면 가끔 이상한걸 발견할 수 있다.

다음과 같이 위치 정보에 관한 enum을 만들어보면, 아래와 같은 경고를 만날 수 있다.

switch status {
	case .notDetermined:
		print("notDetermined")
	case .restricted:
		print("restricted")
	case .denied:
		print("denied")
	case .authorizedAlways:
		print("authorizedAlways")
	case .authorizedWhenInUse:
		print("authorizedWhenInUse")
	case .authorized:
		print("authorized")
}
  • Switch covers known cases, but 'CLAuthorizationStatus' may have additional unknown values, possibly added in future versions
  • Handle unknown values using "@unknown default"

10. @unknown default가 무엇이냐면

현재 버전에서는 enum이 저거밖에 없지만, 추후 업데이트가 되면서 새로운 권한이 생긴다면, 그때는 어떻게 처리를 할 것인가에 대해 묻고 있다. 다시 말해서 저렇게 짜도 문제는 없지만, 언젠가는 문제가 터질 수 있다는 경고. 아래와 같이 추가해준다면 문제가 없다.

switch status {
	case .notDetermined:
		print("notDetermined")
	case .restricted:
		print("restricted")
	case .denied:
		print("denied")
	case .authorizedAlways:
		print("authorizedAlways")
	case .authorizedWhenInUse:
		print("authorizedWhenInUse")
	case .authorized:
		print("authorized")
	@unknown default:
		print("잘 모르겠음")
}

11. 당신이 enum을 만들었는데 자꾸 unknown default를 만들라고 나온다면

귀찮고 만약 앞으로도 enum이 변경될일 없다면 enum앞에 frozen을 붙여봐라! @unknown default 같은 귀찮은 녀석들을 붙일 필요도 없고 컴파일 속도가 향상되는건 덤이다.

@frozen enum SurpriseEnum: Int {
	case one
	case two 
	case three 
}
profile
🍎Apple Developer Academy @ POSTECH 2nd, 🌱SeSAC iOS 4th

0개의 댓글