A range is a concise way to express a sequence of values, most commonly numbers.
Swift provides excellent support for ranges, making it easy to loop through numbers or slice arrays.
There are three primary types of range operators in Swift.
...)The closed range operator a...b defines a range that runs from a to b, and it includes both a and b.
This is highly useful when you want to iterate over every number in a specific boundary.
// Creates a range that includes 1, 2, 3, 4, 5 let myRange = 1...5 print(myRange.contains(5)) // true
..<)The half-open range operator a..<b defines a range that runs from a to b, but it does not include b.
This is particularly useful when working with zero-based arrays, where the length of the array is not a valid index.
// Creates a range that includes 1, 2, 3, 4 (but not 5) let halfOpen = 1..<5 print(halfOpen.contains(5)) // false
One-sided ranges let you omit either the start or the end of the range.
Swift will automatically infer the missing boundary based on the context, such as the size of an array.
let names = ["Anna", "Alex", "Brian", "Jack"]// Slices from index 2 to the end of the array let subset = names[2...] print(subset) // ["Brian", "Jack"]
You can also omit the start, like this: ...2 or ..<2.
Ranges are frequently used in for-in loops to execute a block of code a set number of times.
They are also heavily used to extract portions (slices) of arrays and strings.
Which range operator includes the starting value but excludes the final value?