Operators
## Learning Objectives
- Master arithmetic operators
- Understand comparison operators
- Work with logical operators
- Use range operators
- Learn assignment operators
## Arithmetic Operators
### Basic Math
```swift
let a = 10
let b = 3
let sum = a + b // 13
let difference = a - b // 7
let product = a * b // 30
let quotient = a / b // 3 (integer division)
let remainder = a % b // 1
```
### Floating-Point Division
```swift
let x: Double = 10.0
let y: Double = 3.0
let result = x / y // 3.333...
```
### Unary Operators
```swift
let negative = -5
let positive = +5 // Same as 5
var counter = 0
counter += 1 // 1
counter -= 1 // 0
```
### Compound Assignment
```swift
var score = 100
score += 10 // 110
score -= 20 // 90
score *= 2 // 180
score /= 3 // 60
score %= 5 // 0
```
## Comparison Operators
### Equality
```swift
let equal = (10 == 10) // true
let notEqual = (10 != 5) // true
```
### Relational
```swift
let less = (3 < 5) // true
let greater = (5 > 3) // true
let lessOrEqual = (3 <= 3) // true
let greaterOrEqual = (5 >= 5) // true
```
### Identity
```swift
// === checks if two references point to same instance
class Dog {
var name: String
init(name: String) { self.name = name }
}
let dog1 = Dog(name: "Buddy")
let dog2 = dog1
let sameInstance = (dog1 === dog2) // true
let differentInstance = (dog1 !== dog2) // false
```
## Logical Operators
### AND
```swift
let passed = true
let hasCredits = true
if passed && hasCredits {
print("Can graduate")
}
// Truth table:
// true && true = true
// true && false = false
// false && true = false
// false && false = false
```
### OR
```swift
let isAdmin = false
let isModerator = true
if isAdmin || isModerator {
print("Has access")
}
// Truth table:
// true || true = true
// true || false = true
// false || true = true
// false || false = false
```
### NOT
```swift
let isDisabled = false
if !isDisabled {
print("Is enabled")
}
// Truth table:
// !true = false
// !false = true
```
### Combined
```swift
let age = 25
let hasLicense = true
let hasInsurance = true
if age >= 18 && (hasLicense || hasInsurance) {
print("Can drive")
}
```
## Range Operators
### Closed Range (...)
Includes both endpoints:
```swift
for index in 1...5 {
print(index) // 1, 2, 3, 4, 5
}
// Useful for arrays
let fruits = ["apple", "banana", "cherry"]
for i in 0...2 {
print(fruits[i])
}
```
### Half-Open Range (..<)
Excludes last endpoint:
```swift
for index in 0..<5 {
print(index) // 0, 1, 2, 3, 4
}
// Common with arrays
for i in 0..= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"
```
## Nil Coalescing Operator
Provides default value for optionals:
```swift
let optionalName: String? = nil
let displayName = optionalName ?? "Anonymous"
// displayName = "Anonymous"
let actualName: String? = "Alice"
let greeting = "Hello, \(actualName ?? "Guest")"
// greeting = "Hello, Alice"
```
## Bitwise Operators
### Bitwise NOT
```swift
let bits: UInt8 = 0b10101010
let flipped = ~bits // 0b01010101
```
### Bitwise AND
```swift
let a: UInt8 = 0b1100
let b: UInt8 = 0b1010
let result = a & b // 0b1000
```
### Bitwise OR
```swift
let result = a | b // 0b1110
```
### XOR
```swift
let result = a ^ b // 0b0110
```
### Shift
```swift
let shifted = a << 1 // 0b11000
let shiftedRight = a >> 1 // 0b0110
```
## Operator Precedence
### Precedence Levels
| Level | Operators |
|-------|-----------|
| Highest | Prefix (a, b), Multiplication (*, /, %) |
| | Addition (a, b), Shift (<<, >>) |
| | Bitwise AND (&) |
| | Bitwise XOR (^) |
| | Bitwise OR (`\|`) |
| | Logical AND (&&) |
| | Logical OR (`\|\|`) |
| Lowest | Ternary (a ? b : c), Assignment (a = b) |
### Examples
```swift
let result = 2 + 3 * 4 // 14, not 20
let result2 = (2 + 3) * 4 // 20
let x = true && false || true // true
```
## Overflow Operators
### Default Behavior
```swift
let maxInt = Int.max
// maxInt + 1 // Runtime crash!
```
### Overflow Operator Usage
```swift
let overflowSum = maxInt &+ 1 // Wraps around
let overflowProduct = 100 &* 100 // Wraps on overflow
```
### Wrapping Behavior
## Custom Operators
### Define Operator
```swift
infix operator **
func **(base: Double, exponent: Double) -> Double {
return pow(base, exponent)
}
let result = 2 ** 3 // 8.0
```
### Precedence and Associativity
```swift
infix operator **: MultiplicationPrecedence
precedencegroup MyPrecedence {
higherThan: MultiplicationPrecedence
associativity: left
}
```
## Summary
- Arithmetic: `+`, `-`, `*`, `/`, `%`
- Comparison: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Logical: `&&`, `||`, `!`
- Range: `...` (closed), `..<` (half-open)
- Ternary: `condition ? true : false`
- Nil coalescing: `optional ?? default`
- Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>`
- Use parentheses for clarity
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →