忍者刘米米

9. Enumerations

Enumerations

  • An enumeration defines a common type for a group of related values
  • The value for each case is optional, the value can be a string, a character, or a value of any integer or floating-point type.Unlike C and Objective-C, Swift enumeration cases are not assigned a default integer value when they are created.
  • cases can specify associated values of any type to be stored along with each different case value

Enumeration Syntax

Each enumeration definition defines a brand new type, which name should be with capital and singular rather than plural.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum SomeEnumeration {
// enumeration definition goes here
}

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

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

var directionToHead = CompassPoint.west

directionToHead = .east

Matching Enumeration Values with a Switch Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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"

// a switch statement must be exhaustive or provide default case to cover others
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
// Prints "Mostly harmless"

Associated Values

  • store additional custom information
  • store associated values of any given type, and the value types can be different for each case of the enumeration if needed
  • Extract value from associated value by prefix let orvar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

productBarcode = .qrCode("ABCDEFGHIJKLMNOP")

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).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."

// If all of the associated values for an enumeration case are extracted as constants
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."

Raw Value vs. Associate Value

Item Raw value Associate value
When to set value first define the enumeration set when you create a new instance
value each case is always the same can be different between each case
value type string,character,integer,float any given type

Raw Values

  • default values (called raw values), which are all of the same type.
  • Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.
1
2
3
4
5
6
// stores raw ASCII values alongside named enumeration cases:
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}

Implicitly Assigned Raw Values

  • if type is Int,default value is 0, then increment.
  • if type is String,the implicit value for each case is the text of that case’s name.
1
2
3
4
5
6
7
8
9
10
11
12
13
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

enum CompassPoint: String {
case north, south, east, west
}

let earthsOrder = Planet.earth.rawValue
// earthsOrder is 3

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Initializing from a Raw Value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.uranus

let positionToFind = 11

// failable initializer
if let somePlanet = Planet(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)")
}
// Prints "There isn't a planet at position 11"

Recursive Enumerations

????

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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))

func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}

print(evaluate(product))
// Prints "18"