Swift - Ternary Conditional Operator

Introduction

You can use the If-Else statement to write simple statements like the following:


var day = 5
var openingTime:Int

if day == 6 || day == 7 {
    openingTime = 12
} else {
    openingTime = 9
}

Here, to know the opening time of a store based on the day of the week day.

If it is Saturday (6) or Sunday (7), then the opening time is 12:00 noon; otherwise on the weekday it is 9:00 a.m.

Such a statement could be shortened using the ternary conditional operator, as shown here:

openingTime = (day == 6 || day == 7) ? 12: 9

The ternary conditional operator has the following syntax:

variable = condition ? value_if_true  : value_if_false

It first evaluates the condition. If the condition evaluates to true , the value_if_true is assigned to variable.

Otherwise, the value_if_false is assigned to variable .