Swift Operators
Introduction
Operators are special symbols or phrases that are used to check, change, or combine values. Swift has a rich set of operators that allow you to perform various operations on your data. Understanding operators is a fundamental aspect of programming in Swift, as they enable you to manipulate values and make decisions in your code.
In this tutorial, we'll explore the different types of operators in Swift:
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Range Operators
- Assignment Operators
- Bitwise Operators
- Identity and Nil-Coalescing Operators
Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric values. Swift supports all the standard arithmetic operators.
Basic Arithmetic Operators
let a = 10
let b = 3
// Addition (+)
let sum = a + b // 13
// Subtraction (-)
let difference = a - b // 7
// Multiplication (*)
let product = a * b // 30
// Division (/)
let quotient = a / b // 3 (integer division)
// Remainder (%) - also called modulo
let remainder = a % b // 1 (because 10 = 3*3 + 1)
When working with floating-point numbers, division behaves differently:
let c = 10.0
let d = 3.0
let floatQuotient = c / d // 3.3333333333333335
Compound Assignment Operators
These operators combine an operation with assignment.
var x = 10
// Add and assign
x += 5 // x is now 15 (equivalent to x = x + 5)
// Subtract and assign
x -= 3 // x is now 12 (equivalent to x = x - 3)
// Multiply and assign
x *= 2 // x is now 24 (equivalent to x = x * 2)
// Divide and assign
x /= 4 // x is now 6 (equivalent to x = x / 4)
// Remainder and assign
x %= 4 // x is now 2 (equivalent to x = x % 4)
Unary Plus and Minus Operators
let positiveNumber = +3 // 3
let negativeNumber = -3 // -3
// Unary minus can also negate a value
let y = 5
let negated = -y // -5
Comparison Operators
Comparison operators compare two values and return a Bool
indicating whether the statement is true or false.
let a = 10
let b = 5
// Equal to (==)
let isEqual = a == b // false
// Not equal to (!=)
let notEqual = a != b // true
// Greater than (>)
let greater = a > b // true
// Less than (<)
let less = a < b // false
// Greater than or equal to (>=)
let greaterOrEqual = a >= b // true
// Less than or equal to (<=)
let lessOrEqual = a <= b // false
These operators are frequently used in conditional statements:
let age = 20
if age >= 18 {
print("You can vote.")
} else {
print("You cannot vote yet.")
}
// Output: "You can vote."
Logical Operators
Logical operators modify or combine Boolean logic values.
let isRaining = true
let isCold = false
// NOT operator (!)
let isNotRaining = !isRaining // false
// AND operator (&&)
let stayInside = isRaining && isCold // false
// OR operator (||)
let takeUmbrella = isRaining || isCold // true
Combining Logical Operators
let temperature = 25
let isSunny = true
// Complex logical expression
let goToBeach = isSunny && (temperature > 22) && !isRaining
// true because it's sunny, warm (above 22), and not raining
// Short-circuit evaluation
// Swift evaluates only what's needed - if isRaining is true,
// it won't evaluate the rest of the conditions
let needUmbrella = isRaining || (temperature < 0 && isCold)
// true because isRaining is true
Range Operators
Range operators express a range of values.
Closed Range Operator
The closed range operator (a...b
) defines a range from a
to b
, including both a
and b
.
for i in 1...5 {
print(i)
}
// Output: 1 2 3 4 5
Half-Open Range Operator
The half-open range operator (a..<b
) defines a range from a
to b
, including a
but excluding b
.
for i in 1..<5 {
print(i)
}
// Output: 1 2 3 4
One-Sided Ranges
One-sided ranges specify a range that continues as far as possible in one direction.
let names = ["Anna", "Brian", "Charles", "David", "Eva"]
// From index 2 to the end
let fromCharles = names[2...] // ["Charles", "David", "Eva"]
// From start to index 2 (exclusive)
let toBrian = names[..<2] // ["Anna", "Brian"]
// From start to index 2 (inclusive)
let toCharles = names[...2] // ["Anna", "Brian", "Charles"]
Assignment Operators
The basic assignment operator (=
) assigns a value to a variable.
var x = 10 // Assigns the value 10 to x
As we saw earlier, we can combine assignment with arithmetic operations:
var y = 5
y += 3 // y is now 8
Bitwise Operators
Bitwise operators work with the individual bits of binary numbers. They're less commonly used by beginners but are important for certain tasks.
let bits1: UInt8 = 0b00001111 // 15 in decimal
let bits2: UInt8 = 0b11110000 // 240 in decimal
// Bitwise AND (&)
let andResult = bits1 & bits2 // 0b00000000 or 0
// Bitwise OR (|)
let orResult = bits1 | bits2 // 0b11111111 or 255
// Bitwise XOR (^)
let xorResult = bits1 ^ bits2 // 0b11111111 or 255
// Bitwise NOT (~)
let notBits1 = ~bits1 // 0b11110000 or 240
// Left shift (<<)
let leftShift = bits1 << 2 // 0b00111100 or 60
// Right shift (>>)
let rightShift = bits2 >> 2 // 0b00111100 or 60
Identity and Nil-Coalescing Operators
Ternary Conditional Operator
The ternary conditional operator is a shorthand for an if-else statement:
let age = 15
let canVote = age >= 18 ? "Yes, can vote" : "No, cannot vote"
// "No, cannot vote"
// Equivalent if-else:
// let canVote
// if age >= 18 {
// canVote = "Yes, can vote"
// } else {
// canVote = "No, cannot vote"
// }
Nil-Coalescing Operator
The nil-coalescing operator (??
) provides a default value when an optional value is nil:
let userInput: String? = nil
let userNameOrDefault = userInput ?? "Guest"
// userNameOrDefault is "Guest" because userInput is nil
let anotherInput: String? = "John"
let anotherName = anotherInput ?? "Guest"
// anotherName is "John" because anotherInput is not nil
Practical Examples
Example 1: Calculating a Discount
func calculateFinalPrice(originalPrice: Double, discountPercentage: Double) -> Double {
let discountAmount = originalPrice * (discountPercentage / 100)
return originalPrice - discountAmount
}
let shirtPrice = 25.0
let discount = 20.0 // 20% discount
let finalPrice = calculateFinalPrice(originalPrice: shirtPrice, discountPercentage: discount)
print("Original price: $\(shirtPrice)")
print("After \(discount)% discount: $\(finalPrice)")
// Output:
// Original price: $25.0
// After 20.0% discount: $20.0
Example 2: Age-based Permission System
func checkPermission(age: Int) -> String {
let canVote = age >= 18
let canDrink = age >= 21
let canRentCar = age >= 25
var permissions = ""
if canVote {
permissions += "Can vote. "
}
if canDrink {
permissions += "Can drink alcohol. "
}
if canRentCar {
permissions += "Can rent a car."
}
return permissions.isEmpty ? "No adult permissions." : permissions
}
print(checkPermission(age: 16)) // "No adult permissions."
print(checkPermission(age: 19)) // "Can vote. "
print(checkPermission(age: 23)) // "Can vote. Can drink alcohol. "
print(checkPermission(age: 30)) // "Can vote. Can drink alcohol. Can rent a car."
Example 3: Temperature Converter
func convertTemperature(degrees: Double, from inputScale: String, to outputScale: String) -> Double {
var celsius: Double = 0.0
// Convert input to celsius first
switch inputScale.lowercased() {
case "celsius", "c":
celsius = degrees
case "fahrenheit", "f":
celsius = (degrees - 32) * 5/9
case "kelvin", "k":
celsius = degrees - 273.15
default:
return Double.nan // Not a number
}
// Convert celsius to output scale
switch outputScale.lowercased() {
case "celsius", "c":
return celsius
case "fahrenheit", "f":
return celsius * 9/5 + 32
case "kelvin", "k":
return celsius + 273.15
default:
return Double.nan // Not a number
}
}
let freezingFahrenheit = convertTemperature(degrees: 32, from: "F", to: "C")
print("32°F = \(freezingFahrenheit)°C") // "32°F = 0.0°C"
let boilingCelsiusToK = convertTemperature(degrees: 100, from: "C", to: "K")
print("100°C = \(boilingCelsiusToK)K") // "100°C = 373.15K"
Summary
In this tutorial, we've covered Swift's operators, which are essential tools for manipulating data in your programs:
- Arithmetic operators perform mathematical calculations (
+
,-
,*
,/
,%
) - Comparison operators evaluate relationships between values (
==
,!=
,>
,<
,>=
,<=
) - Logical operators combine Boolean conditions (
&&
,||
,!
) - Range operators express value sequences (
...
,..<
, one-sided ranges) - Assignment operators set and modify variable values (
=
, compound assignment) - Bitwise operators manipulate individual bits in binary numbers (
&
,|
,^
,~
,<<
,>>
) - Identity and Nil-Coalescing operators offer concise conditional expressions (
?:
,??
)
Understanding these operators will help you write cleaner, more efficient Swift code and solve a variety of programming problems.
Practice Exercises
- Write a function that calculates the area and perimeter of a rectangle using arithmetic operators.
- Create a program that determines if a year is a leap year using logical and comparison operators.
- Use the ternary operator to write a function that returns "Pass" if a score is 60 or above, otherwise "Fail".
- Write a function that uses bitwise operators to swap two numbers without using a temporary variable.
- Create a program that uses range operators to print a countdown from 10 to 1.
- Implement a tip calculator that takes a bill amount and a tip percentage, returning the total bill.
- Write a function that uses the nil-coalescing operator to provide default values for optional parameters.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)