FullerPrime FullerPrime - 4 months ago 11
Swift Question

How do I make my if statement more efficient?

Writing some swift code for an app and whilst it works fine, I can't help but think it's ugly and can be improved upon, I'm still new and always looking for ways to improve my code so any help is appreciated. In context it's for a slider and a couple of labels.

var value1 = Int (sender.value)

value1text.text = "\(value1)"

var value2:Int

if value1 <= 5 {
endText.text = "\(7 - value1)"
} else if value1 == 6 {
value1 = 2
value2 = 6
endText.text = "\(value1)/\(value2)"
} else if value1 == 7 {
value1 = 2
value2 = 5
endText.text = "\(value1)/\(value2)"
} else if value1 == 8 {
value1 = 2
value2 = 4
endText.text = "\(value1)/\(value2)"
} else if value1 == 9 {
value1 = 2
value2 = 3
endText.text = "\(value1)/\(value2)"
} else if value1 == 10 {
value1 = 2
value2 = 2
endText.text = "\(value1)/\(value2)"
}


My vars are better named in my app, just renamed for easier reading (hopefully).

Answer

Use a Switch statement.

var value1 = Int(sender.value) //TODO: Give me a better name!

value1text.text = String(value1) //Don't use String interpolation solely for conversion

switch (value1) {
case Int.min...5:
    endText.text = String(7 - value1)
case let x where 6...10 ~= x:
    value1 = 2
    value2 = 12 - x
    endText.text = "\(value1)/\(value2)"
default:
    fatalError("What happens now?")
}