Swift Enumerations
An enumeration (Enumeration) is used to describe "a finite set of possible values".
For example, a week has only seven days and an order has only a few statuses; using an enum is much safer than string constants: a misspelled case is caught at compile time.
Swift's enums are more powerful than C's: they can carry associated values, methods, computed properties, and can conform to protocols.
Enums are value types, copied by value when assigned or passed as arguments, just like structs.
Definition and case
Use the enum keyword to define an enumeration, with each value listed using case.
Multiple cases can be written on the same line, separated by commas.
Example
import Foundation
// Define the weekdays in a week
enum
RunoobWeekday
{
case
monday, tuesday, wednesday, thursday, friday
}
func plan
(
_ day
:
RunoobWeekday
)
String
{
switch
day
{
case
.
monday
:
return
"Monday: regular meeting"
case
.
tuesday
, .
wednesday
, .
thursday
:
return
"Midweek: development"
case
.
friday
:
return
"Friday: release"
}
}
(
plan
(
.
wednesday
)
)
(
plan
(
.
friday
)
)
Running result:
周中:开发
周五:发布
There are two ways to reference an enum value: the full form RunoobWeekday.wednesday, and in contexts where the type is known it can be shortened to .wednesday.
When calling plan(.wednesday) above, the parameter type is already determined, so the enum name is omitted.
Working with switch
The most common use of an enum is together with switch, which is also where it's safer than string constants.
switch checks whether all cases are covered; missing one is a compile error, so you don't need to write default.
Conversely, default can be omitted only when the switch is exhaustive (all cases listed, or the two cases of Bool); for open types like Int it must be written.
Example
import Foundation
enum
RunoobGrade
:
Int, CaseIterable
{
case
a
=
90
, b
=
80
, c
=
60
// Enums can have computed properties
var isPass
:
Bool
{
rawValue
=
60
}
// Enums can also have methods
func label
(
)
String
{
switch
self
{
case
.
a
:
return
"Excellent"
case
.
b
:
return
"Good"
case
.
c
:
return
"Pass"
}
}
}
// Use with where for filtering
for
grade in RunoobGrade.
allCases
where grade.
rawValue
=
80
{
(
"(grade.rawValue) -> (grade.label())"
)
}
(
RunoobGrade.
c
.
isPass
)
Running result:
90 -> 优秀
80 -> 良好
true
Inside an enum, self represents the current value, so label() can switch directly on self.
Associated values
A raw value means "each case corresponds to a fixed value"; associated values are the opposite: each case can carry its own data, and cases of different types and different numbers can be mixed in the same enum.
It's well suited to describing data of variable shape such as "operation results".
Example
import Foundation
// Associated values: each case can carry data of different types
enum
RunoobResponse
{
case
success
(
data
:
String
)
case
failure
(
code
:
Int, message
:
String
)
case
loading
}
func handle
(
_ response
:
RunoobResponse
)
{
switch
response
{
case
.
success
(
let data
)
:
(
"success: (data)"
)
case
.
failure
(
let code, let message
)
:
(
"failure [(code)]: (message)"
)
case
.
loading
:
(
"Loading..."
)
}
}
handle
(
.
success
(
data
:
"response from www.runoob.com"
)
)
handle
(
.
failure
(
code
:
404
, message
:
"Page not found"
)
)
handle
(
.
loading
)
Running result:
成功:来自 www.runoob.com 的响应
失败 [404]:页面不存在
加载中...
When extracting the value, use case .success(let data) to bind the associated value to a local constant, then use it in the branch.
If you only care about a certain associated value, you can also use where to add a conditional filter, or bind only part of it.
Note:Associated values and raw values can't be mixed on the same case. A case either carries an associated value or has a raw value, not both.
Raw values and RawRepresentable
A raw value lets each case correspond to a fixed value; the type can be a string, character, integer, or floating-point number, and must be consistent within the same enum.
An enum with raw values automatically conforms to RawRepresentable, and thus gains a rawValue property and a failable init?(rawValue:) initializer.
Example
import Foundation
// Raw values: all cases in the same enum must have raw values of the same type
enum
RunoobStatus
:
Int
{
case
created
=
1
case
processing
case
finished
}
enum
RunoobSite
:
String
{
case
home
=
"www.runoob.com"
case
name
=
"RUNOOB"
}
let status
=
RunoobStatus.
processing
(
"rawValue = (status.rawValue)"
)
// When no raw value is written, it increments from the previous value
// Look up a case by raw value, returning an optional
if
let finished
=
RunoobStatus
(
rawValue
:
3
)
{
(
"Found case: (finished)"
)
}
if
let unknown
=
RunoobStatus
(
rawValue
:
99
)
{
(
unknown
)
}
else
{
(
"99 has no corresponding case"
)
}
(
RunoobSite.
home
.
rawValue
)
Running result:
rawValue = 2
找到 case:finished
99 没有对应的 case
www.runoob.com
For integer raw values you only write the first; the rest increment automatically, so processing's rawValue is 2.
When a string raw value isn't written, it defaults to the case name itself; here it's explicitly specified as a URL.
RunoobStatus(rawValue:) used for reverse lookup returns an optional, and returns nil if not found, so you must handle it with if let or the nil-coalescing operator.
CaseIterable and allCases
To make all cases of an enum into an iterable collection, just make it conform to CaseIterable.
The compiler automatically synthesizes an allCases static property, of array type, with order consistent with the declaration order.
Example
import Foundation
// CaseIterable: automatically synthesizes allCases, with order consistent with declaration order
enum
RunoobPlanet
:
String, CaseIterable
{
case
mercury
=
"Mercury"
case
venus
=
"Venus"
case
earth
=
"Earth"
}
(
RunoobPlanet.
allCases
.
count
)
for
planet in RunoobPlanet.
allCases
{
(
"(planet.rawValue) -> (planet)"
)
}
Running result:
3
水星 -> mercury
金星 -> venus
地球 -> earth
Note that printing planet directly gives the case name mercury, not the raw value; to get the raw value you must write planet.rawValue.
allCases is common in scenarios like "rendering all options into a list", for example dropdown options on a settings page.
Note:Cases with associated values can't have allCases synthesized automatically, because the compiler can't generate a uniform array element for them. In that case you need to write allCases by hand.
Recursive enums: indirect
Some data structures are inherently recursive, such as expression trees: an addition node contains two more expressions.
If an enum case directly holds itself, the compiler can't determine its size; you must add indirect to make that layer use indirect storage.
Example
import Foundation
// Recursive enum: a case uses itself internally, so indirect is required to break infinite size
indirect
enum
RunoobExpression
{
case
number
(
Int
)
case
add
(
RunoobExpression, RunoobExpression
)
case
multiply
(
RunoobExpression, RunoobExpression
)
}
func evaluate
(
_ expression
:
RunoobExpression
)
Int
{
switch
expression
{
case
.
number
(
let value
)
:
return
value
case
.
add
(
let left, let right
)
:
return
evaluate
(
left
)
evaluate
(
right
)
case
.
multiply
(
let left, let right
)
:
return
evaluate
(
left
)
evaluate
(
right
)
}
}
// Represents (1 + 2) * 3
let expression
=
RunoobExpression.
multiply
(
.
add
(
.
number
(
1
)
, .
number
(
2
)
)
,
.
number
(
3
)
)
(
evaluate
(
expression
)
)
Running result:
9
Writing indirect before enum means all cases of the enum may recurse; you can also write it before a single case to make only that case use indirect storage.
For computation, traverse with a recursive function: return the value on .number, and for operators recursively evaluate and then combine.
@unknown default
Another case: the enum isn't defined by you but comes from a system framework or another module.
Such enums may gain new cases in future framework upgrades; if the switch hard-codes all current cases, a new version will fail to compile.
@unknown default is the fallback branch prepared for this scenario.
Example
import Foundation
// @unknown default: for enums defined in other modules (such as system frameworks), covering newly added cases in the future
func describe
(
_ result
:
ComparisonResult
)
String
{
switch
result
{
case
.
orderedSame
:
return
"exactly the same"
case
.
orderedAscending
:
return
"the former is smaller"
case
.
orderedDescending
:
return
"the former is larger"
@unknown
default
:
return
"a case added in the future"
}
}
(
describe
(
"runoob"
.
compare
(
"RUNOOB"
)
)
)
(
describe
(
"abc"
.
compare
(
"abd"
)
)
)
Running result:
前者更大
前者更小
String comparison uses Unicode order, with lowercase letters after their uppercase counterparts, so "runoob" is greater than "RUNOOB".
Note:@unknown default It can only be placed at the end of a switch, and only makes sense for enums "defined in external modules and subject to new cases". Using it on your own enum makes the compiler warn that the switch is not exhaustive.
Common questions
Below are some common questions about using enums.
Can an enum have initializers?
Yes. An enum can have designated and convenience initializers, and can also use init?(rawValue:) with raw values.
Enums are value types, so assigning to self in an initializer must likewise ensure all stored properties have initial values.
Can an enum conform to protocols?
Yes, and it's very common. Conforming to CaseIterable gives you allCases; conforming to Codable allows direct encoding and decoding.
When an enum with raw values conforms to Codable, the encoded result is the raw value.
How to choose between raw values and associated values?
Use a raw value when you need to exchange a fixed value with an external system, such as a status code returned by an API.
Use associated values when you need to carry structured data and each case carries different content, such as success and failure of a network request.
How are enums compared?
Enums without associated values can be compared directly with ==, and the compiler automatically synthesizes equality.
Enums with associated values need to conform to Equatable; as long as the associated values are themselves comparable, it can be synthesized automatically.
Is the order of allCases guaranteed?
Yes, the order is the declaration order of the cases; unlike dictionaries, you can rely on it.