How the Range Operators Work in Swift

How the Range Operators Work in Swift



In Swift, the Range object allows you to define a sequence of values within a certain boundary.


Closed Range Operator

The closed range operator (...) creates a range that includes both the start and the end values. It’s inclusive of both boundaries.


let numbers = 1...5
print(numbers) // output: 1...5        

This code creates a range of numbers from 1 to 5, inclusive of 5.



for number in 1...5 {
    print(number)
}

// output:
// 1
// 2
// 3
// 4
// 5        

You can also loop through this range with a for-loop.



for number in (1...5).reversed() {
    print(number)
}

// output:
// 5
// 4
// 3
// 2
// 1        

To reverse the order of the numbers, you use the .reversed() method.



if numbers.contains(7) {
    
    print("Yes we have a winner")
} else {
    print("No, 7 is not here")
}

// output: No, 7 is not here        

As Range follows the Collections protocol, you can also use the .contains(_:) instance method to check for the presence of a specific value.



let negativeNumber = -2 ... -1
print(negativeNumber) // output: -2...-1        

For negative numbers, precede the end value with white space or wrap it in parentheses.


Half-Open Range Operator


for number in (1..<5) {
    print(number)
}

// output:
// 1
// 2
// 3
// 4        

The half-open range operator (..<) creates a range that includes the start value but excludes the end value. It is half-open because the upper boundary is not included.

This is the same code as before, however, we’re using the half-open range operator to print out numbers from 1 to 5 — exclusive of 5.


One-Sided Range Operator


let numArray = [1, 2, 3, 4, 5, 5, 6, 7]

print(numArray) // output: [1, 2, 3, 4, 5, 5, 6, 7]

let firstSubArray = numArray[...3]

print(firstSubArray) // output: [1, 2, 3, 4]

let secondSubArray = numArray[4...]

print(secondSubArray) // output: [5, 5, 6, 7]        

Swift also supports one-sided ranges, where the range is either unbounded on one end. This is useful when you want to specify a range that extends indefinitely in one direction, such as when working with collections.


Recap of Range Operators:

  • Closed range operator (...): Includes both start and end values.
  • Half-open range operator (..<): Includes the start value, excludes the end value.
  • One-sided ranges: Extend from one end and go either up to or from the given index.


As usual, I recommend you open up your Xcode playground and explore more ways of working with Range Operators.

要查看或添加评论,请登录