Sanghyuk's Dev

[Swift] Enumerations

iOS/Swift2018. 5. 23. 20:13



※ Enumerations

- 연관된 값의 그룹에 대해 공통 타입을 정의한 뒤 type-safe 하게 해당 값들을 사용 가능

- Enumeration Type 이름은 Pascal Case 로 작성한다.

- 각 case 는 Camel Case 로 작성한다.

enum CompassPoint {
    case north
    case south
    case east
    case west
}

enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

var directionToHead1 = CompassPoint.west
directionToHead1 = .east

var directionToHead2: CompassPoint = .north


※ Matching Enumeration Values

let directionToHead = CompassPoint.south

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")
}

let somePlanet = Planet.earth

switch somePlanet {
case .earth:
    print("Mostly harmless")
default:
    print("Not a safe place for humans")
}


※ Associated Values

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
type(of: productBarcode)

print(productBarcode)

switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
    print("QR code: \(productCode).")
}

switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
    print("QR code: \(productCode).")
}


※ Raw Value

- Strings, Characters, or any of the Integer or Floating-point number types

- raw value 는 해당 Enumeration 내에서 반드시 고유한 값이어야 함.

//enum ASCIIControlCharacter {
//  case tab
//  case lineFeed
//  case carriageReturn
//}
//ASCIIControlCharacter.tab
//ASCIIControlCharacter.lineFeed
//ASCIIControlCharacter.carriageReturn

enum ASCIIControlCharacter1: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

enum Weekday: Int {
    case sunday, monday, tuesday, wednesday, thursday, friday, saturday
}

Weekday.wednesday
Weekday.wednesday.rawValue

enum WeekdayName: String {
    case sunday, monday, tuesday, wednesday, thursday, friday, saturday
}

WeekdayName.monday
WeekdayName.monday.rawValue


- Implicitly Assigned Raw Values

enum WeekdayAgain: Int {
    case sunday, monday = 100, tuesday = 101, wednesday, thursday, friday, saturday
//  case sunday = 0, monday = 1, tuesday = 2, wednesday, thursday, friday, saturday
}

WeekdayAgain.sunday
WeekdayAgain.sunday.rawValue

WeekdayAgain.wednesday
WeekdayAgain.wednesday.rawValue

enum WeekdayNameAgain: String {
    case sunday, monday = "mon", tuesday = "tue", wednesday, thursday, friday, saturday
}

WeekdayNameAgain.sunday
WeekdayNameAgain.sunday.rawValue

WeekdayNameAgain.wednesday
WeekdayNameAgain.wednesday.rawValue


- Initializing from a Raw Value

enum PlanetIntRaw: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

PlanetIntRaw(rawValue: 7)

let possiblePlanet = PlanetIntRaw(rawValue: 2)
//let positionToFind = 7
let positionToFind = 11

//PlanetIntRaw(rawValue: 5)
//PlanetIntRaw(rawValue: 10)

if let somePlanet = PlanetIntRaw(rawValue: positionToFind) {
    switch somePlanet {
    case .earth:
        print("Mostly harmless")
    default:
        print("Not a safe place for humans")
    }
} else {
    print("There isn't a planet at position \(positionToFind)")
}


※ Nested

- Function

enum Device: String {
    case iPhone, iPad, tv, watch
  
    func printType() {
        switch self {
        case .iPad, .iPhone, .tv:
            print("device :", self)
        case .watch:
            print("apple Watch")
        }
    }
}

let iPhone = Device.iPhone
iPhone.printType()


- Enumerations

enum Wearable {
    enum Weight: Int {
        case light = 1
        case heavy = 2
    }
    enum Armor: Int {
        case light = 2
        case heavy = 4
    }
    case helmet(weight: Weight, armor: Armor)
    case boots
  
    func attributes() -> (weight: Int, armor: Int) {
        switch self {
        case .helmet(let w, let a):
            return (weight: w.rawValue * 2, armor: a.rawValue * 4)
        case .boots:
            return (2, 4)
        }
    }
}

var woodenHelmet = Wearable.helmet(weight: .light, armor: .heavy)
woodenHelmet.attributes()
print(woodenHelmet)

let boots = Wearable.boots


※ Mutating

enum NewRemoteControl {
    case on, off
  
    mutating func next() {
        switch self {
        case .off:
            self = .on
        case .on:
            self = .off
        }
    }
}

var newRemoteControl = NewRemoteControl.on
newRemoteControl.next()
newRemoteControl.next()


※ Recursion (재귀)

- Recursive Function

자기 자신을 재참조하는 함수

// for Loop
var count = 0
for _ in 0..<5 {
    count += 1
}

// recursion
count = 0

func recursiveFunction() {
    guard count != 5 else { return }
    count += 1
    print(count)
  
    recursiveFunction()   // <--------
    print("lastline", count)
}

recursiveFunction()


※ Recursive Enumerations

- 자기 자신을 참조하는 Enumeration 형식

//enum ArithmeticExpression {
//    case number(Int)
//    case addition(ArithmeticExpression, ArithmeticExpression)
//    case multiplication(ArithmeticExpression, ArithmeticExpression)
//}


//enum ArithmeticExpression {
//    case number(Int)
//    indirect case addition(ArithmeticExpression, ArithmeticExpression)
//    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
//}

indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
    case multiplication(ArithmeticExpression, ArithmeticExpression)
}


let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))


'iOS > Swift' 카테고리의 다른 글

[Swift] Set  (0) 2018.05.23
[Swift] Dictionary  (0) 2018.05.23
[Swift] Array  (0) 2018.05.23
[Swift] Control Transfer Statement  (0) 2018.05.23
[Swift] Tuples  (0) 2018.05.23