What are unary, binary, and ternary Operators? The answer to this question is surprisingly simple.

Unary Operators in Swift

A unary operator is an operator that operates on a single operand. An operand can be a value or an expression. Take a look at this example.

// Value
let a = 10
-a  // -10

// Value
let b = -11
-b  // 11

// Expression
(a + b)
-(a + b)

We define a constant a with value 10 and a constant b with value -11. The unary minus operator toggles the sign of a and b. The last example also illustrates how the unary minus operator can be used on an expression. Even though Swift also defines a unary plus operator, it doesn't affect the numeric value it operates on.

// Value
let a = 10
+a  // -10

// Value
let b = -11
+b  // 11

// Expression
(a + b)
+(a + b)

Swift defines many more unary operators. Another common unary operator is the logical NOT operator. It toggles a boolean value as you can see in the example below.

let c = true
!c  // false

let d = false
!d  // true

Binary Operators

As the name suggests, a binary operator operates on two operands. Swift's arithmetic operators are examples of binary operators.

1 + 2   // 3
3 - 4   // -1
5 * 6   // 30
7 / 8   // 0

Swift's remainder operator is another example of a binary operator. It returns the remainder of a division as you can see in this example.

9 % 4   // 1

Ternary Operator

Swift defines a single ternary operator, the ternary conditional operator. A question mark and a colon separate the three targets of the operation. If the condition preceding the question mark evaluates to true, the expression before the colon is executed and returned. If the condition preceding the question mark evaluates to false, the expression after the colon is executed and returned.

let numberOfLegs = 4

// Ternary Conditional Operator
let animal = numberOfLegs > 2 ? "mammal" : "bird"   // "mammal"

A ternary conditional operator can always be written as an if-else statement as you can see in the updated example below.

let numberOfLegs = 4

let animal: String

// If-Else Statement
if numberOfLegs > 2 {
    animal = "mammal"
} else {
    animal = "bird"
}