Enumerations
μ΄κ±°νμ κ΄λ ¨λ κ°λ€μ μ μνκ³ , μ½λμμμ νμ μΈμ΄ν νκ² μ¬μ©κ°λ₯νλ€. μ€μννΈμμλ κ°κ°μ μΌμ΄μ€μ κ°μ μ 곡ν νμκ° μμΌλ©°, λ¬Έμμ΄,λ¬Έμ,μ μ λ±μΌλ‘ μμκ°μ μ€μ ν΄ μ€ μ μλ€.
λλ μ΄κ±°νμ κ°κ°μ μΌμ΄μ€λ λͺ¨λ νμ μ μ°κ΄κ°μ μ€μ ν΄ μ€ μ μλ€.
μ΄κ±°ν ꡬ문 (Enumeration Syntax)
enum CompassPoint {
case north
case south
case east
case west
}
μ΄κ±°ν μμ (north, south, east, west)μ μ΄κ±°ν μΌμ΄μ€ (enumeration cases) μ΄λ€. μ΄κ±°ν μΌμ΄μ€λ₯Ό λνλ΄κΈ° μν΄ case ν€μλλ₯Ό μ¬μ©νλ€.
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
νμ€λ‘λ μ μ κ°λ₯νλ€.
Switch ꡬ문μμ μ΄κ±°ν κ° μΌμΉ (Matching Enumeration Values with Switch Statement)
Switch ꡬ문μ μ΄κ±°νκ³Ό ν¨κ» νμ©ν μ μλ€.
directionToHead = .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")
}
// Prints "Watch out for penguins"
μ΄κ±°ν μΌμ΄μ€ λ°λ³΅ (Iterating over Enumeration Cases)
μ΄κ±°νμ λͺ¨λ μΌμ΄μ€λ₯Ό μμ§νλλ° μ μ©νλ€. CaseIterable
μ±ννμ¬ νμ±ν νλ€. μ£Όλ‘allCase
νλ‘νΌν°μ ν¨κ» μ¬μ©λλ€.
enum Beverage: CaseIterable {
case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")
// Prints "3 beverages available"
μ°κ΄λ κ° (Associated Values)
μ΄κ±°νμ μ°κ΄κ°μ ꡬ체μ μΈ μ 보λ₯Ό μ μ₯νκΈ° μν΄ μ¬μ©νλ€. μΌμ΄μ€λ³λ‘ κ°κ°μ νΉμ§μ΄ μ‘΄μ¬νκ³ , μ΄λ₯Ό νμ©ν νμκ° μμ λλ μΌμ΄μ€λ§λ€ μ μ₯ν ννλ₯Ό μ μν λ μ¬μ©νλ€. λν νλμ μΌμ΄μ€μ μλ‘λ€λ₯Έ μ°κ΄κ°μ μ μ₯ν μ μλ€.
enum Computer {
case cpu(core: Int, ghz: Double)
case ram(Int, String)
case hardDisk(gb: Int)
}
μμκ° (Raw Values)
μ«μλλ λ¬Έμμ΄κ³Ό 맀μΉμμΌ μ΄κ±°νμ λ³΄λ€ μμ λ‘κ² μ¬μ©ν μ μκ² λμμ€λ€.
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
μμμ μΌλ‘ ν λΉλ μμκ°
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// mercury = 1 μ μμμΌλ‘ λ€μ μΌμ΄μ€μλ μλμΌλ‘ λ€μ μ«μκ° μμκ°μΌλ‘ ν λΉλλ€.
μμκ°μΌλ‘ μ΄κΈ°ν (Initializing from a Raw Value)
let possiblePlanet = Planet(rawValue: 7)
// 7μ μμκ°μ κ°μ§ .uranusκ° μ΄κΈ°ν λμ΄ μμμ ν λΉλλ€.