上QQ阅读APP看书,第一时间看更新
Adding methods to enums
The first feature of a Swift enum that makes them so much more than just names of integer values (or any other type) is the ability to add methods to them.
Let us create an enum of traffic light colors, which also defines a method that can be called on any instances of that enum type:
enum TrafficLightColor
{
case red, amber, green
func inFrench() ->String
{
switch self
{
case .red:
return "Rouge"
case .amber:
return "Jaune"
case .green:
return "Vert"
}
}
}
Note that no default case is necessary here, since our switch statement is exhaustive in terms of the possible TrafficLightColor cases.
Now, we have an enum that encapsulates not only the definition of the new type and its cases, but also a method with which we can have the instance return a String object that is computed from within the enum itself:
let stop: TrafficLightColor = .red
print(stop.inFrench())
Already it is becoming clear that there are many situations in which we would traditionally have created a class, but for which we can instead create a much more lightweight enum.
Note that enum instances are passed by value, not by reference.