본문 바로가기
iOS/Swift

[Swift] 열거형과 원싯값 (feat. CaseIterable)

by Dev.Andy 2023. 7. 25.

머리말

참고 자료

열거형(Enumerations)

열거형의 정의

공식 문서에서 정의한 열거형이란 아래와 같다.

열거형은 연관된 값들의 묶음에 대하여 공통된 타입을 정의하고, 코드에서 타입 세이프한 방식으로 그 값들을 작업할 수 있도록 한다.
An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

열거형 구문(Enumeration Syntax)

enum이라는 키워드로 열거형을 정의하고, case라는 키워드로 각 케이스(경우)에 대하여 정의한다.

enum Gender {
    case male
    case female
}

쉼표(,)로 구분하여 한 줄에 정의할 수도 있다.

enum Media {
    case movie, drama, animation
}

열거형의 특징

⭐️ 컴파일 시점에 enum case를 확인할 수 있어서, 미리 오류를 인지할 수 있다.

원싯값(Raw Value)

원싯값의 정의

모든 열거형의 케이스를 동일한 타입으로 정의하여, 기본값을 할당하는 것을 뜻한다.

원싯값의 특징

멤버와 값을 분리할 수 있다(?)

enum Media: String {
    case movie, drama, animation
}

var myContents: Media = .movie

/// if 문으로 해 보기
if myContents == .movie {
    print("You selected \\(myContents.rawValue)")
} else if myContents == .drama {
    print("You selected \\(myContents.rawValue)")
} else if myContents == .animation {
    print("You selected \\(myContents.rawValue)")
} else {
    print("You selected \\(myContents.rawValue)")
}

// switch 문으로 해 보기
/// ⭐️ enumeration처럼 default의 경우가 아예 없을 경우에는 해당 조건을 생략 가능하다
switch myContents {
case .movie: print("MOVIE")
case .drama: print("DRAMA")
case .animation: print("ANIMATION")
}

CaseIterable

CaseIterable의 정의

열거형의 케이스들을 반복할 수 있게 하는(iterating over enumeration cases) 프로토콜이다.

CaseIterable의 특징

allCases

  • allCases라는 프로퍼티를 이용해 해당 열거형에 대한 모든 케이스를 하나의 컬렉션으로 만들 수 있다.
  • 따라서 이를 이용하여 인덱스 접근을 할 수 있다.
enum NewWords: Int, CaseIterable {
    case JMT, LOL, LMAFO
}

/// CaseIterable 없이 직접 만들 떄
let wordList: [NewWords] = [.JMT, .LOL, .LMAFO]
print(wordList) // [__lldb_expr_70.NewWords.JMT, __lldb_expr_70.NewWords.LOL, __lldb_expr_70.NewWords.LMAFO]
print(wordList[0]) // JMT
print(wordList[1]) // LOL

/// CaseIterable을 이용할 때
let wordListIterable = NewWords.allCases
print(wordListIterable) // [__lldb_expr_76.NewWords.JMT, __lldb_expr_76.NewWords.LOL, __lldb_expr_76.NewWords.LMAFO]
print(wordListIterable[0]) // JMT
print(wordListIterable[1]) // LOL

print(NewWords.JMT.rawValue) // 0
print(NewWords.LOL.rawValue) // 1
print(NewWords.LMAFO.rawValue) // 2

 

댓글