Site icon CodeWithSwift

Operators in Swift

Types of Operators

1. Assignment Operator

Assigns the value on the right-hand side to the variable or constant on the left-hand side. (=)

 let x = 18 // Assigns 18 to x
 var y = 8
 y = x // Now y is equal to 18

2. Arithmetic Operators

Swift provides standard arithmetic operators for mathematical operations:

let a = 15
let b = 4
print(a + b)  // Output: 19 (Addition)
print(a - b)  // Output: 11 (Subtraction)
print(a * b)  // Output: 60 (Multiplication)
print(a / b)  // Output: 3 (Division)
print(a % b)  // Output: 3 (Modulo)

3. Compound Assignment Operators

These combine an operation with assignment, allowing you to update a variable by performing an operation on it:

var x = 10
x += 5       // Equivalent to `x = x + 5`
print(x)     // Output: 15

x -= 3       // Equivalent to `x = x - 3`
print(x)     // Output: 12

x *= 2       // Equivalent to `x = x * 2`
print(x)     // Output: 24

x /= 4       // Equivalent to `x = x / 4`
print(x)     // Output: 6

x %= 5       // Equivalent to `x = x % 5`
print(x)     // Output: 1
Exit mobile version