fs_tigre fs_tigre - 1 month ago 14
Swift Question

Perform action based on one of three choices in a more Object Oriented way

I need to perform a calculation based on one of three options the user can select, I haven't created any real code because I'm not sure what method to use that is more common in a more OOP than my spaghetti code below.

What would be the most common way to keep track of

measurementType
based on the following code? I have never used Enums in any language and I was wondering if this would be a good fit for them.

Any suggestion?

var measurementType:String = ""

let pounds = "Pounds"
let kilograms = "Kilograms"
let quantity = "Quantity"

// User selection
measurementType = pounds

// Perform calculation based on user's selection
if measurementType == kilograms{
print("Calculation for Kilograms")
}else if(measurementType == pounds){
print("Calculation for Pounds")
}else{
print("Calculation for Quantity")
}

Answer

I wouldn't really call that spaghetti code, but sure, you can use enum in this case. Also, you might want to use a switch statement instead of multiple if-else.

enum MeasurementType {
    case Pounds
    case Kilograms
    case Quantity
}

var measurementType: MeasurementType = .Pounds

switch measurementType {
    case .Pounds:
        print("Calculation for Pounds")
    case .Kilograms:
        print("Calculation for Kilograms")
    case .Quantity:
        print("Calculation for Quantity")
    default:
        print("?")
        //or use () / break if the default doesn't interest you
}