Game Development Reference
In-Depth Information
enum DaysOfTheWeek: Int {
case Sunday = 0, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday
}
You define each member of an
enum
using a
case
. Notice the way you are defining your
members. You have a comma-separated list with only the first member being set. If the
type of the
enum
is an
Int
raw value (raw values are the values you assign to an
enum
member), then you have to set only the first value and Swift will determine the remaining
values. To see how this
enum
is used, copy it and the following snippet into your
main.swift
and run it:
var today = DaysOfTheWeek.Friday
println("Today is \(today.rawValue).")
You will see the following output.
Today is 5.
Notice
println()
in the second line. You are invoking the
toRaw()
method on the
enum
. This function is a built-in function of every
enum
that will return whatever the raw
value of each member of the
enum
has stored as its value.
You can use other raw values such as
String
s and
Float
s, but you will have to expli-
citly set each value.
enum RGBColors : String {
case Red = "Red", Green = "Green", Blue = "Blue"
}
If an enumeration does not have a meaningful raw value, then you don't have to assign it a
value at all. Each member of the
enum
will have a value assigned to it by Swift.
enum RGBColors {
case Red, Green, Blue
}
Another nice thing about Swift enumerations is that they can have methods associated
with them. Take a look at the new
DaysOfTheWeek
enumeration: