안녕하세요:)
오늘은 동일한 이름에 속한 상수 그룹을 선언하고 다양하게 매칭시키는 방법에 대해 알아보도록 하겠습니다.
enum TypeName { // 문법: 열거형은 독립적인 형식, UppercamelCase
case caseName
case caseName, caseName
}
enum Alignment {
case left
case center
case right
}
Alignment.left
Alignment.center
Alignment.right
var textAlignment = Alignment.center
textAlignment = .left
textAlignment = .justify // 케이스에 선언하지 않을 걸 저장하면 에러가 발생합니다.
enum Direction {
case north
case south
case east
case west
}
Direction.north
let directionToHead: Direction = .east
switch directionToHead {
case .north:
print("북쪽 입니다.")
case .south:
print("남쪽 입니다.")
case .east:
print("동쪽 입니다.")
case .west:
print("서쪽 입니다.")
} // 모든 경우의 수를 처리해주었기 때문에 default를 생략했습니다.
enum TypeName: RawValueType {
case caseName = Value
case caseName, caseName
}
enum Alignment: Int {
case left
case right = 100
case center
} // 원시값의 자료형이 Int로 선언됩니다.
// 원시값에 접근
Alignment.left.rawValue // 0
Alignment.right.rawValue // 100
Alignment.center.rawValue // 101
Alignment(rawValue: 0) // 파라미터로 rawValue를 전달하면 동일한 rawValue를 가진 case가 생성됩니다.
Alignment(rawValue: 200) // 이 값을 가진 케이스는 없으니까 nil이 리턴됩니다.
enum Weekday: String {
case sunday
case monday = "MON"
case tuesday
case wednesday
case thursday
case friday
case saturday
}
Weekday.sunday.rawValue // sunday원시값의 자료형을 문자열로 선언하고 원시값을 생략하면 케이스 이름과 동일한 원시값이 저장됩니다.
Weekday.monday.rawValue // MON