Swift Assignment Operators
Assigning and modifying values in Swift
📝 What are Assignment Operators?
Assignment operators in Swift are used to assign values to variables and constants. They include basic assignment (=) and compound assignment operators that combine assignment with arithmetic operations for cleaner, more efficient code.
// Basic assignment
var score = 100
var name = "Swift"
Types of Assignment Operators
Basic Assignment
Assigns a value to a variable
var x = 10
let y = "Hello"
Addition Assignment
Adds and assigns the result
var a = 5
a += 3 // a = 8
Subtraction Assignment
Subtracts and assigns the result
var b = 10
b -= 4 // b = 6
Multiplication Assignment
Multiplies and assigns the result
var c = 3
c *= 4 // c = 12
🔹 Basic Assignment Operator
The basic assignment operator (=) assigns the value on the right to the variable on the left:
// Assigning values
var playerName = "Alice"
var playerScore = 1500
var isActive = true
// Assigning one variable to another
var highScore = playerScore
print(highScore) // Output: 1500
Output:
🔹 Compound Assignment Operators
Compound assignment operators combine assignment with arithmetic operations:
🔸 Addition Assignment (+=)
var points = 100
points += 50 // Same as: points = points + 50
print(points) // Output: 150
var message = "Hello"
message += " World" // String concatenation
print(message) // Output: Hello World
Output:
Hello World
🔸 Subtraction Assignment (-=)
var health = 100
health -= 25 // Same as: health = health - 25
print(health) // Output: 75
Output:
🔸 Multiplication Assignment (*=)
var multiplier = 3
multiplier *= 4 // Same as: multiplier = multiplier * 4
print(multiplier) // Output: 12
Output:
🔸 Division Assignment (/=)
var total = 20.0
total /= 4.0 // Same as: total = total / 4.0
print(total) // Output: 5.0
Output:
🔹 Remainder Assignment (%=)
The remainder assignment operator finds the remainder and assigns it:
var number = 17
number %= 5 // Same as: number = number % 5
print(number) // Output: 2 (17 divided by 5 leaves remainder 2)
Output:
🔹 Practical Examples
Real-world usage of assignment operators:
// Game scoring system
var playerScore = 0
playerScore += 100 // Player gets 100 points
playerScore += 50 // Player gets 50 more points
playerScore -= 25 // Player loses 25 points
print("Final Score: \(playerScore)") // Output: Final Score: 125
// Shopping cart calculation
var cartTotal = 29.99
cartTotal += 15.50 // Add another item
cartTotal *= 1.08 // Add 8% tax
print("Total with tax: $\(cartTotal)") // Output: Total with tax: $49.1292
Output:
Total with tax: $49.1292