In Swift, there is a wide range of operators that can be used to perform operations on values. These operators can be divided into different categories based on the number of targets they have and the kind of operation they perform.
Unary, Binary, and Ternary Operators
Operators are categorized based on the number of targets they have. Unary operators have one target, binary operators have two targets, and the ternary operator is the only one with three targets.
Assignment Operator
The assignment operator (=
) is used to assign a value to a variable or to assign the value of one variable to another. For example:
var age = 8
var another = age
Arithmetic Operators
Swift provides several binary arithmetic operators, including +
, -
, *
, /
(division), and %
(remainder). These operators can be used to perform arithmetic operations on numbers. For example:
1 + 1 // 2
2 - 1 // 1
2 * 2 // 4
4 / 2 // 2
4 % 3 // 1
4 % 2 // 0
The -
operator can also be used as a unary minus operator:
let hotTemperature = 20
let freezingTemperature = -20
The +
operator can be used to concatenate string values:
"Roger" + " is a good dog"
Compound Assignment Operators
Compound assignment operators combine the assignment operator with arithmetic operators. They provide a shorthand way of performing an arithmetic operation and assigning the result back to the variable. For example:
var age = 8
age += 1
Comparison Operators
Swift defines several comparison operators, including ==
, !=
, >
, <
, >=
, and <=
. These operators compare two values and return a boolean value (true
or false
) indicating the result of the comparison. For example:
let a = 1
let b = 2
a == b // false
a != b // true
a > b // false
a <= b // true
Range Operators
Range operators are used in loops to define a range of values. There are two types of range operators: ...
(inclusive range) and ..<
(half-open range). For example:
0...3 // 0, 1, 2, 3
0..<3 // 0, 1, 2
0...count // 0 to count (inclusive)
0..<count // 0 to count-1 (exclusive)
Here’s an example of how range operators can be used in a loop:
let count = 3
for i in 0...count {
// loop body
}
Logical Operators
Swift provides several logical operators, including !
(NOT), &&
(AND), and ||
(OR). These operators are used to perform logical operations and return a boolean value. For example:
let condition1 = true
let condition2 = false
!condition1 // false
condition1 && condition2 // false
condition1 || condition2 // true
Logical operators are commonly used in if
statements for conditional evaluation:
if condition1 && condition2 {
// if body
}
Swift also allows you to define your own operators and specify how they work on your own custom types.