Swift Operators

Swift Operators

Operators are special symbols or keywords that perform operations on one, two, or three operands.

You use operators to perform calculations, check conditions, assign values, and more.

Swift supports the standard C operators and improves upon them to eliminate common coding errors.


Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Arithmetic Example:

let a = 10
let b = 3
print(a + b) // Outputs 13
print(a % b) // Outputs 1 (Remainder of 10 divided by 3)

Assignment Operators

The basic assignment operator is =, which assigns the value on the right to the variable on the left.

Swift also provides compound assignment operators that combine assignment with another operation.

Assignment Example:

var score = 10
score += 5  // Equivalent to: score = score + 5
print(score) // Outputs 15

Comparison Operators

Comparison operators are used to compare two values. They always evaluate to a boolean value (true or false).

Comparison Example:

let x = 5
let y = 10
print(x == y) // Outputs false
print(x < y)  // Outputs true

Logical Operators

Logical operators modify or combine boolean logic values.

Logical Example:

let isAdult = true
let hasTicket = false
print(isAdult && hasTicket) // Outputs false
print(!isAdult) // Outputs false

Exercise

What does the `%` operator do in Swift?