Enum is the way to delimit a certain aspect of your code, you can use it to specify a finite number of possibilities that may occur in your code, eg:
A simple calculator, you can for example do a function by passing the two values and the operation:
func calculate(lhs: Double, rhs: Double, operation: String) -> Double {
switch operation {
case "+":
return lhs + rhs
default:
return lhs - rhs
}
}
but this way if you are giving the possibility to pass anything and you will never know for sure if what is coming is always an operation and whenever it will not fall into subtraction, with an enum you will always know what you will receive because will be of the type enum, so it does not 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, ie you will use in more than one class such as values:
enum StaticValues: Double {
case pi = 3.1415926
case inch = 2.54 // cm
case mile = 1.609344 // metter
}
and using its "raw" value:
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 like:
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 not instantiate and the MathOperator class could someone, so the enum is more secure.