πŸ¦… Swift

Enumerations

KiwiπŸ’» 2022. 6. 15. 20:34

μ—΄κ±°ν˜•μ€ κ΄€λ ¨λœ 값듀을 μ •μ˜ν•˜κ³ , μ½”λ“œμ•ˆμ—μ„œ νƒ€μž… 세이프 ν•˜κ²Œ μ‚¬μš©κ°€λŠ₯ν•˜λ‹€. μŠ€μœ„ν”„νŠΈμ—μ„œλŠ” 각각의 μΌ€μ΄μŠ€μ— 값을 μ œκ³΅ν•  ν•„μš”κ°€ μ—†μœΌλ©°, λ¬Έμžμ—΄,문자,μ •μˆ˜ λ“±μœΌλ‘œ μ›μ‹œκ°’μ„ μ„€μ •ν•΄ 쀄 수 μžˆλ‹€.

λ˜λŠ” μ—΄κ±°ν˜•μ˜ 각각의 μΌ€μ΄μŠ€λŠ” λͺ¨λ“  νƒ€μž…μ˜ 연관값을 μ„€μ •ν•΄ 쀄 수 μžˆλ‹€.

μ—΄κ±°ν˜• ꡬ문 (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κ°€ μ΄ˆκΈ°ν™” λ˜μ–΄ μƒμˆ˜μ— ν• λ‹Ήλœλ‹€.

'πŸ¦… Swift' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

Properties  (0) 2022.07.04
Structures and Classes  (0) 2022.06.22
Closures  (0) 2022.06.15
Functions  (0) 2022.06.01
Control Flow  (0) 2022.06.01