Lesson 7Swift Basics

Operators

Swift Operators

Operators are symbols that perform operations on values. Let's explore the main types!

Arithmetic Operators

+

Add

-

Subtract

*

Multiply

/

Divide

%

Remainder

Comparison Operators

==

Equal

!=

Not equal

>

Greater

<

Less

>=

<=

Logical Operators

&&

AND

Both must be true

||

OR

One must be true

!

NOT

Flips the value

main.swift
// Arithmetic operators
let a = 10
let b = 3

print(a + b)  // 13 (addition)
print(a - b)  // 7 (subtraction)
print(a * b)  // 30 (multiplication)
print(a / b)  // 3 (integer division)
print(a % b)  // 1 (remainder/modulo)

// Comparison operators
print(a == b)  // false (equal to)
print(a != b)  // true (not equal to)
print(a > b)   // true (greater than)
print(a < b)   // false (less than)
print(a >= b)  // true (greater or equal)
print(a <= b)  // false (less or equal)

// Logical operators
let isStudent = true
let hasHomework = false

print(isStudent && hasHomework)  // false (AND)
print(isStudent || hasHomework)  // true (OR)
print(!isStudent)                // false (NOT)

// Compound assignment
var score = 100
score += 10  // score = score + 10 = 110
score -= 5   // score = score - 5 = 105
score *= 2   // score = score * 2 = 210
print(score) // 210

Try It Yourself!

Calculate the area of a rectangle (width × height) and check if it's greater than 100!