/

Swift Operators: A Comprehensive Guide

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
2
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
2
3
4
5
6
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:

1
2
let hotTemperature = 20
let freezingTemperature = -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
2
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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
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:

1
2
3
4
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:

1
2
3
4
5
6
7
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:

1
2
3
if condition1 && condition2 {
// if body
}

Swift also allows you to define your own operators and specify how they work on your own custom types.

tags: [“Swift”, “Operators”]