Skip to main content

Working with Operators

1. Using Arithmetic Operators (+, -, *, /, %)

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 7 42
/ Division 15 / 3 5
% Modulus (remainder) 17 % 5 2

Example: Basic Arithmetic Operations

let a = 10
let b = 3
print(a + b) // 13
print(a - b) // 7
print(a * b) // 30
print(a / b) // 3
print(a % b) // 1

2. Using Comparison Operators (==, !=, <, >, <=, >=)

Operator Description Example Result Type
== Equal to 5 == 5 Bool
!= Not equal to 5 != 3 Bool
< Less than 3 < 5 Bool
> Greater than 5 > 3 Bool
<= Less than or equal to 5 <= 5 Bool
>= Greater than or equal to 5 >= 3 Bool

Example: Comparing Values

let a = 10
let b = 20

if a < b {
    print("a is less than b")
}

if a == 10 {
    print("a equals 10")
}

3. Using Logical Operators (&&, ||, !)

Operator Description Example Result
&& Logical AND true && false false
|| Logical OR true || false true
! Logical NOT !true false

Example: Combining Conditions

let isLoggedIn = true
let hasPermission = false

if isLoggedIn && hasPermission {
    print("Access granted")
} else if isLoggedIn || hasPermission {
    print("Limited access")
} else {
    print("Access denied")
}

Example: Negation Usage

let isRaining = true
let isSunny = !isRaining

if isSunny {
    print("It's sunny outside")
} else {
    print("It's raining or cloudy")
}

4. Using Compound Assignment Operators (+=, -=)

Compound assignment operators in Swift combine an arithmetic operation with an assignment, allowing you to modify a variable's value in a more concise way.

Operator Description Example Equivalent To
+= Adds the right operand to the left operand and assigns the result to the left operand var a = 5; a += 3; a = a + 3
-= Subtracts the right operand from the left operand and assigns the result to the left operand var b = 10; b -= 4; b = b - 4
*= Multiplies the left operand by the right operand and assigns the result to the left operand var c = 6; c *= 2; c = c * 2
/= Divides the left operand by the right operand and assigns the result to the left operand var d = 15; d /= 3; d = d / 3
%= Calculates the remainder of dividing the left operand by the right operand and assigns the result to the left operand var e = 17; e %= 5; e = e % 5

Example: Using Compound Assignment Operators

var score = 100
score += 10   // Equivalent to: score = score + 10
print(score)  // Output: 110

var count = 50
count -= 5    // Equivalent to: count = count - 5
print(count)  // Output: 45

5. Using Ternary Conditional Operator (?:)

The ternary conditional operator is a concise way to write an if-else statement. It takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false.

Operand Description Example
condition A boolean expression that evaluates to true or false age >= 18
valueIfTrue The value to return if the condition is true "Adult"
valueIfFalse The value to return if the condition is false "Minor"

Example: Basic Ternary Operator Usage

let age = 20
let status = age >= 18 ? "Adult" : "Minor"
print(status) // Prints: Adult

Example: Nested Ternary Operator

let score = 85
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"
print(grade) // Prints: B
Note: The ternary operator is useful for simple conditions but can reduce readability if overused or nested too deeply.

6. Using Range Operators (..., ..<)

Range operators in Swift are used to create ranges of values. They are particularly useful for iterating over sequences or defining ranges in collections.

Operator Description Example Result
... Inclusive range operator 1...5 Range from 1 to 5, inclusive
..< Half-open range operator 1..<5 Range from 1 to 4, excluding 5

Example: Using Range Operators in a Loop

for i in 1...5 {
    print(i)
}
// Output:
// 1
// 2
// 3
// 4
// 5

Example: Using Half-Open Range

let numbers = Array(0..<5)
print(numbers) // [0, 1, 2, 3, 4]

7. Using Bitwise Operators (&, |, ^, ~)

Example: Bitwise Operations

let a: Int = 5    // Binary: 101
let b: Int = 3    // Binary: 011

let andResult = a & b     // Result: 1 (Binary: 001)
let orResult = a | b      // Result: 7 (Binary: 111)
let xorResult = a ^ b     // Result: 6 (Binary: 110)
let notResult = ~a        // Result: -6 (Two's complement)

print("a & b = \\(andResult)")
print("a | b = \\(orResult)")
print("a ^ b = \\(xorResult)")
print("~a = \\(notResult)")
Operator Description Example
& Bitwise AND 5 & 3 = 1
| Bitwise OR 5 | 3 = 7
^ Bitwise XOR 5 ^ 3 = 6
~ Bitwise NOT ~5 = -6
Note: Bitwise operators work on the binary representation of integers.

8. Using Nil-Coalescing Operator (??)

The nil-coalescing operator (??) provides a way to return a default value when an optional is nil.

Expression Description Example
optionalValue ?? defaultValue Returns the value of optionalValue if it is not nil, otherwise returns defaultValue.
let name: String? = nil
let displayName = name ?? "Anonymous"
print(displayName) // Prints "Anonymous"
Note: The right-hand side of ?? is only evaluated if the left-hand side is nil.

9. Using Identity Operators (===, !==)

Operator Description Usage Notes
=== Identity equality operator obj1 === obj2 Checks if two variables refer to the same instance in memory
!== Identity inequality operator obj1 !== obj2 Checks if two variables refer to different instances in memory

Example: Identity Operator Usage

let str1 = "Hello"
let str2 = "Hello"
let str3 = str1

print(str1 === str2) // false - different string instances
print(str1 === str3) // true - same instance reference
Note: Unlike ==, which compares values, === compares object identity.

10. Implementing Custom Operators

Custom operators allow you to define new operators for your types, extending Swift's built-in operator functionality.

Operator Description Example
prefix Defines a prefix operator prefix operator ++
infix Defines an infix operator infix operator +-: AdditionPrecedence
postfix Defines a postfix operator postfix operator ++

Example: Defining a Custom Infix Operator

infix operator <+>: AdditionPrecedence

func <+> (left: String, right: String) -> String {
    return "\(left) and \(right)"
}

let result = "Hello" <+> "World"
print(result) // Output: Hello and World

Example: Defining a Prefix Operator

prefix operator ++

struct Counter {
    var value: Int = 0
}

func ++ (counter: inout Counter) {
    counter.value += 1
}

var counter = Counter()
++counter
print(counter.value) // Output: 1

Was this article helpful?