🔥 열거형과 switch 문

303자
4분

열거형의 각 case 값은 switch 문을 사용해 매칭할 수 있습니다. 예를 들어, CompassPoint 열거형을 사용해 봅시다.

swift
enum CompassPoint {
    case north
    case south
    case east
    case west
}
 
var directionToHead = CompassPoint.south
swift
enum CompassPoint {
    case north
    case south
    case east
    case west
}
 
var directionToHead = CompassPoint.south

여기서 directionToHead 변수는 CompassPoint 열거형의 값 중 하나를 가질 수 있죠. 이제 switch 문을 사용해 directionToHead의 값에 따라 다른 동작을 수행해 볼까요?

swift
switch directionToHead {
case .north:
    print("Lots of planets have a north") // 많은 행성에는 북쪽이 있어요
case .south:
    print("Watch out for penguins") // 펭귄을 조심하세요
case .east:
    print("Where the sun rises") // 해가 뜨는 곳이에요
case .west:
    print("Where the skies are blue") // 하늘이 푸른 곳이죠
}
// "Watch out for penguins" 출력
swift
switch directionToHead {
case .north:
    print("Lots of planets have a north") // 많은 행성에는 북쪽이 있어요
case .south:
    print("Watch out for penguins") // 펭귄을 조심하세요
case .east:
    print("Where the sun rises") // 해가 뜨는 곳이에요
case .west:
    print("Where the skies are blue") // 하늘이 푸른 곳이죠
}
// "Watch out for penguins" 출력

이 코드를 다음과 같이 읽을 수 있습니다:

"directionToHead의 값을 살펴봅시다. 만약 .north와 같다면, "Lots of planets have a north"를 출력합니다. .south와 같다면, "Watch out for penguins"를 출력하는 거죠."

이런 식으로 .east.west에 대해서도 처리합니다.

제어 흐름에서 설명한 것처럼, 열거형의 case를 다룰 때 switch 문은 반드시 모든 경우를 포괄해야 합니다. 만약 .west에 대한 case를 생략한다면, 이 코드는 컴파일되지 않을 거예요. 왜냐하면 CompassPoint의 모든 case를 고려하지 않았기 때문이죠. 완전성을 요구하는 것은 열거형의 case가 실수로 누락되는 것을 방지합니다.

그런데 때로는 열거형의 모든 case에 대해 case를 제공하는 것이 적절하지 않을 수 있어요. 이럴 때는 default case를 제공해 명시적으로 다루지 않은 나머지 case들을 처리할 수 있습니다.

swift
enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
 
let somePlanet = Planet.earth
 
switch somePlanet {
case .earth:
    print("Mostly harmless") // 대체로 무해해요
default:
    print("Not a safe place for humans") // 인간에게 안전한 곳은 아니에요
}
// "Mostly harmless" 출력
swift
enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
 
let somePlanet = Planet.earth
 
switch somePlanet {
case .earth:
    print("Mostly harmless") // 대체로 무해해요
default:
    print("Not a safe place for humans") // 인간에게 안전한 곳은 아니에요
}
// "Mostly harmless" 출력

이렇게 하면 somePlanet.earth인 경우에는 "Mostly harmless"를 출력하고, 나머지 모든 경우에는 "Not a safe place for humans"를 출력하게 됩니다.

열거형과 switch문을 활용하면 코드의 가독성과 안전성을 높일 수 있답니다. 열거형으로 사용 가능한 값의 범위를 명확히 하고, switch문으로 모든 경우를 빠짐없이 처리하도록 강제할 수 있으니까요.

YouTube 영상

채널 보기
미들웨어 vs 가드, 왜 NestJS에서는 가드가 더 똑똑할까? | NestJS 가이드
Pro펑터, 입력과 출력을 동시에 다루는 펑터 | 프로그래머를 위한 카테고리 이론
존 매카시가 들려주는 인공지능의 탄생 이야기
NestJS 커스텀 데코레이터 인자 전달 및 파이프 검증 활용법 | NestJS 가이드
C++ 속의 펑터 | 프로그래머를 위한 카테고리 이론
Writer 펑터와 클라이슬리 카테고리 | 프로그래머를 위한 카테고리 이론
입력을 전처리하는 Functor - Contravariant와 contramap 이해하기 | 프로그래머를 위한 카테고리 이론
NestJS 커스텀 데코레이터, createParamDecorator 사용 | NestJS 가이드