Welcome back to CodeYourCraft! Today, we're diving into one of Swift's powerful features: Range Operators (..., ..<). By the end of this lesson, you'll have a solid understanding of how to use these operators to create and manipulate ranges, making your code more efficient and expressive.
Let's start with the basics.
In Swift, range operators allow us to define a sequence of values, from a start point to an end point, with a certain step size (optional). This is particularly useful when dealing with collections, arrays, and loops.
The two range operators in Swift are:
... - Closed range operator..< - Half-open range operatorLet's explore each operator with some examples.
...) š”The closed range operator creates an inclusive range, meaning it includes the end value in the range.
let closedRange = 1...5
print(closedRange) // Output: Range<Int>.ClosedRange (1 to 5)In this example, we've created a closed range from 1 to 5. You can access each value in the range using the .first and .last properties:
for number in closedRange {
print(number)
}Output:
1
2
3
4
5
š” Pro Tip: Closed range is useful when you need to iterate over all the values in the range, including the end value.
..<) š”The half-open range operator creates a non-inclusive range, meaning it does not include the end value in the range.
let halfOpenRange = 1..<5
print(halfOpenRange) // Output: Range<Int>.HalfOpenRange (1, 5)In this example, we've created a half-open range from 1 to 5. Similar to the closed range, you can access each value in the range using the .first and .upperBound properties:
for number in halfOpenRange {
print(number)
}Output:
1
2
3
š” Pro Tip: Half-open range is useful when you need to iterate over all the values in the range, excluding the end value.
In addition to the range operators, Swift allows you to create custom ranges using the stride(from:through:by:) function.
let customRange = stride(from: 2, through: 10, by: 2)
print(customRange) // Output: Stride<Int> (2, 2)In this example, we've created a custom range starting from 2, ending at 10, with a step size of 2. You can access each value in the range using the .next() function:
for number in customRange {
print(number)
}Output:
2
4
6
8
10
š” Pro Tip: Custom ranges are useful when you need to create ranges with a specific step size.
Range operators are commonly used in Swift's for-in loops to iterate over collections and custom ranges:
let numbers = Array(1...5)
for number in numbers {
print(number * 2)
}Output:
2
4
6
8
10
In this example, we've created an array from a closed range and used it in a loop to multiply each number by 2.
What is the difference between a closed range and a half-open range?
With this lesson, you now have a solid understanding of how to use range operators in Swift. As you continue your coding journey, you'll find these operators to be invaluable when dealing with collections, loops, and custom ranges. Happy coding! š¤š¼