독립적 자료형
열거형을 사용하는 이유
코드의 가독성과 안정성이 높아진다.
(왼쪽 정렬은 0으로 표현하고 다음 정렬은 1로 표현한다.)
let left = "left"
let center = "center"
let right = "right"
var alignment = center
if alignment == "Center" {
}
enum TypeName {
case caseName
case caseName, caseName
}
enum Alignment {
case left
case right
case center
}
Alignment.center
Alignment.right
var textAlignment = Alignment.center
textAlignment = .left // 열거형 이름 생략 가능 .은 생략 불가
if textAlignment == .center{
print("center")
} else if textAlignment == .left {
print("left")
} else {
print("right")
}
// 열거형은 주로 switch문으로 많이 사용
switch textAlignment {
case .left:
print("left")
case . right:
print("right")
case . center:
print("center")
}
enum TypeName: RawValueType {
case caseName = Value
}
enum Alignment: Int {
case left
case right = 100
case center
}
Alignment.left.rawValue
Alignment.right.rawValue
Alignment.center.rawValue
// 원시값을 바꾸는 것은 불가능
Alignment(rawValue: 0) // 동일한 값을 갖는 생성자
Alignment(rawValue: 200)
enum Weekday: String {
case sunday
case monday = "MON" // 원시값 직접 저장
case tuesday
case wednesday
case thursday
case friday
case saturday
}
Weekday.sunday.rawValue
Weekday.monday.rawValue
enum ControlChar: Character {
case tab = "\t"
case newLine = "\n"
}