What is half-open range in Swift?

In Swift, we can create a range of values between two numeric values using the ... range operator.

Half-open range

a..<b

A half-open range includes all the values in the interval from the lower bound a to the upper bound b, excluding the upper bound b.

Example

import Swift
let numbers = 0..<5
print("The Half-Open Range is ", numbers)
print( "Checking if 3 is present in the range ",numbers.contains(3))
print( "Checking if 5 is present in the range ",numbers.contains(10))

In the code above:

  • We used the ..< range operator to create a half-open rangeAn interval of values from a lower bound to upper bound, excluding upper bound (in this case, 5) from 1 to 5. Now the numbers will contain the values of 1,2,3,4.

  • We checked if the 3 and 5 are present in the numbers range.

    • 3 is present in the range
    • 5 is not present in the range because the half-open range doesn’t include the upper bound value.

Use half-open range to slice array

import Swift
var fruits = ["apple", "orange", "banana", "watermelon", "Avocado"]
print("Tha fruits array is \(fruits)");
var slicedFruits = fruits[0..<2]
print("\nTha slicedFruits from index 1 to 3 is \(slicedFruits)");

In the code above, we created a fruits array with five elements. Then, we sliced the fruits array from index 0 to 2 with the half-open range operator (<..). This will slice the elements of index 0 and 1. Index 2 is skipped.

Use half-open range in for loop

import Swift
var numbers = [1,2,3,4,5]
print("The array is :- \(numbers)")
print(numbers.count)
for index in 0..<numbers.count {
print(numbers[index])
}

In the above for loop, we used the half-open range as:

0..<numbers.count

This will loop from index 0 to numbers.count-1.

Use half-open range in if condition

import Swift
if (0..<5).contains(5) {
print(" 5 present in the range 0..<5")
} else{
print(" 5 is not present in the range 0..<5")
}

In the code above:

  • We created a half-open range of 0..<5.
  • We used the if statement to check if 5 is present in the range.
  • We found that in our case, 5 is not present in the range, because in the half-open range 0..<5 the upper bound value 5 will be excluded.

Free Resources