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

Asked

Viewed 95 times

0

Good guys, I’m studying hard to start developing an app in Swift 4 for a job interview, but the Type Enum left me a little, almost nothing, however, still confused.

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

1 answer

1


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.