Enumeration Swift 4 - What is its usefulness and how does it work for IOS development?

0

Well guys, I'm studying a lot to start developing an application in Swift 4 for a job interview, but the Type Enum left me a little, almost nothing, but still confused.

I wanted to know a bit more about this Swift 4 language element, how it works, some examples of Type Enum     

asked by anonymous 10.08.2018 / 22:17

1 answer

1

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.

    
13.08.2018 / 22:55