Steve Ives Steve Ives - 6 months ago 20
Swift Question

Should I always replace if...then...else with a ternary in Swift?

If I can replace an

if...then...else
with a ternary, should I do so? Or does it come down to which of the two is the most easy to read and clear?

E.g. change:

If condition {
doSomething
} else {
doSomethingElse
}


to

condition ? doSomething : doSomethingElse


How about with variable assignments :

If condition {
myProperty += 1
} else {
myProperty -= 1
}


to:

myProperty = condition ? myProperty + 1 : myProperty - 1


Edit : Not looking for peoples' opinion on which they prefer, but whether or not there is an accepted professional practice to replace if...then...else with a ternary if possible.

Answer

Since both are valid and there is no difference in performance, the goal is readability.

Use a ternary conditional for a simple inline decision.

For anything that wouldn't be appropriate inline or more complicated than basic arithmetic, it would probably be more readable to use normal conditional statements

Apple has a great example of this in the Swift 2.2 docs

Examples from Swift 2.2 Apple docs:

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90

I would say the above is just as readable as below and much cleaner.

let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
    rowHeight = contentHeight + 50
} else {
    rowHeight = contentHeight + 20
}
// rowHeight is equal to 90
Comments