What is closed range in Swift?

In Swift, we can use the ... range operator to create a range of values between two numeric values. It is used to check if a value is present in the range or to create a range of values.

Closed range

a...b

A closed range includes all the values in the interval from the lower bound a to the upper bound b (including the upper bound b).

Example

import Swift
let numbers = 0...5
print(numbers)
print( "Checking if 3 is present in the range ",numbers.contains(3))
print( "Checking if 10 is present in the range ",numbers.contains(10))
print( "Checking if 5 is present in the range ",numbers.contains(5))

In the code above, we have:

  • Used the ... range operator to create a closed rangeAn interval of values from a lower bound to upper bound (including upper bound). from 1 to 5(included). Now, the numbers will contain the values of 1,2,3,4,5.

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

Use closed 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 0 to 2 is \(slicedFruits)");

In the above code, we have created a fruits array with five elements. Then, we used the ... range operator to slice the fruits array from index 0 to 2.

Use closed range in for loop

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

In the for loop above, we have used the closed range as:

0...numbers.count - 1

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

Use closed range in if condition

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

In the code above, we have:

  • Created a closed range of 0...5.
  • Checked if 5 is present in the range using the if statement.

Free Resources