Chapter 15: Enumerations

大綱

Declaring an enumeration

Deciphering an enumeration in a function

  • 如何在function中使用enum

  • enum中所有case都需要被處理,不然compiler會報錯

    • 少用default

    There is another huge benefit to getting rid of the default. If in a future update someone added .undecember or .duodecember to the Month enumeration, the compiler would automatically flag this and any other switch statement as being non-exhaustive, allowing you to handle this specific case.

Code completion prevents typos

  • you’ll never have a typo in your member values. Xcode provides code completion:

Raw values

  • Swift enum values are not backed by integers as a default. That means january is itself the value

  • you can associate a raw value with each enumeration case simply by declaring the raw value in the enumeration declaration

Accessing the raw value

Initializing with the raw value

  • use the raw value to instantiate an enumeration value with an initializer.

  • There’s no guarantee that the raw value you submitted exists in the enumeration, so the initializer returns an optional.

String raw values

Unordered raw values

Associated values

  • 這個是enum中最強的特性,也是讓enum變得無敵好用的工具。

  • 實用時機

    • Each enumeration case has zero or more associated values.

    • The associated values for each enumeration case have their own data type.

    • You can define associated values with label names like you would for named function parameters.

Enumeration as state machine

  • a state machine, meaning it can only ever be a single enumeration value at a time, never more

Iterating through all cases

  • When you add : CaseIterable your enumeration gains a class method called allCases

Enumerations without any cases

  • Enumerations are quite powerful. They can do most everything a structure can, including having custom initializers, computed properties and methods

Optionals

  • Optionals are really enumerations with two cases:

    • .none means there’s no value.

    • .some means there is a value, which is attached to the enumeration case as an associated value.

Key points

  • An enumeration is a list of mutually exclusive cases that define a common type.

  • Enumerations provide a type-safe alternative to old-fashioned integer values.

  • You can use enumerations to handle responses, store state and encapsulate values.

  • CaseIterable lets you loop through an enumeration with allCases.

  • Uninhabited enumerations can be used as namespaces and prevent the creation of instances.

Last updated