Swift Operators: A Comprehensive Guide
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:
1 | var age = 8 |
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 + 1 // 2 |
The -
operator can also be used as a unary minus operator:
1 | let hotTemperature = 20 |
The +
operator can be used to concatenate string values:
1 | "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:
1 | var age = 8 |
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:
1 | let a = 1 |
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:
1 | 0...3 // 0, 1, 2, 3 |
Here’s an example of how range operators can be used in a loop:
1 | let count = 3 |
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:
1 | let condition1 = true |
Logical operators are commonly used in if
statements for conditional evaluation:
1 | if condition1 && condition2 { |
Swift also allows you to define your own operators and specify how they work on your own custom types.
tags: [“Swift”, “Operators”]