Enum is the way to delimit certain aspect of your code, you can use it to specify a finite number of possibility that may occur in your code, example:
a simple calculator, Voce can for example make a function by passing the two values and operation:
func calculate(lhs: Double, rhs: Double, operation: String) -> Double {
switch operation {
case "+":
return lhs + rhs
default:
return lhs - rhs
}
}
but that way if you are giving the possibility to pass anything and never know for sure if what is coming is always an operation and whenever it is not will fall in subtraction, with an In you will always know what you will receive because it will be of type Enum, so you don’t necessarily need a default, since you have control of all possibilities as in the example:
enum MathOperator {
case sum
case subtraction
case multiplication
case division
}
class ViewController: UIViewController {
func calculate(lhs: Double, rhs: Double, operation: MathOperator) -> Double{
switch operation {
case .sum:
return lhs + rhs
case .subtraction:
return lhs - rhs
case .multiplication:
return lhs * rhs
case .division:
return lhs / rhs
}
}
you can use Enum to define global static variables, that is you will use in more than one class as for example values:
enum StaticValues: Double {
case pi = 3.1415926
case inch = 2.54 // cm
case mile = 1.609344 // metter
}
and using its value "raw":
print("20 polegadas é igual a: ", StaticValues.inch * 20, "mm")
the difference between using this Enum and a common class with values stored in static constants such as:
class StaticValues {
static let pi = 3.1415926
static let inch = 2.54 // cm
static let mile = 1.609344 // metter
}
is that an Enum you can’t instantiate and the Mathoperator class someone could, so Enum is safer.