What is the difference between a unary, binary, and ternary operator? Someone might ask you this question during your next job interview. In this tutorial, you learn about unary, binary, and ternary operators, and I show you a few examples. Let's start with unary operators.

Unary Operators

A unary operator is an operator that operates one one operand. An operand? An operand is the item in an expression the operator acts upon. Let's take a look at an example. In this example, - is the operator and 10 is the operand. The negation operator operates on 10.

-10

Swift also defines the logical NOT operator you are probably already familiar with. In this example, we use the logical NOT operator to invert a boolean value.

let isValid = true
let isInvalid = !isValid

Swift also defines the bitwise NOT operator to invert the bits of a binary number. Take a look at this example.

let a: UInt8 = 0b00001111
let b = ~a

Binary Operators

If a unary operator operates on one operand, then you can guess what the difference is with a binary operator. A binary operator operates on two operands. Examples are the +, -, *, and / operators you are familiar with.

let a = 2
let b = 5

a + b
a - b
a * b
a / b

The difference between a unary operator and a binary operator is the number of operands the operators acts upon. A unary operator acts upon one operand. A binary operator acts upon two operands.

Ternary Operator

Swift also defines a ternary operator. It acts upon three operands. Because Swift defines only one ternary operator, the conditional operator, it is often referred to as the ternary operator. The ternary operator is often used as shorthand for an if-else statement.

It consists of a condition, a true expression and a false expression. In this example, we assign a value to c. If a is smaller than b, then the value of b is assigned to c. If a is greater than b, then the value of a is assigned to c.

let a = 1
let b = 2

let c = a > b ? a : b

The condition is a > b. The true expression is a and the false expression is b. In this example, the true and false expressions are simple, but you can make them as complex as you want ... in theory. The best practice is to only use the ternary operator for simple expressions. Use an if-else statement if things get complex.

Prefix and Suffix Unary Operators

The operators we covered so far are prefix unary operators. This simply means that they are prepended to the operand. Earlier versions of Swift defined two suffix unary operators, ++ and --. The increment (++) and decrement (--) operators incremented and decremented the value of a variable respectively. These operators were removed in Swift 4.

The compiler throws an error if you use the ++ or -- operators.

What Is the Difference Between a Unary, Binary, and Ternary Operator?

Use the += and -= operators instead.

var a = 1
a += 1