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 Swiftlet numbers = 0...5print(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 fromclosed range An interval of values from a lower bound to upper bound (including upper bound). 1 to 5(included). Now, thenumberswill contain the values of1,2,3,4,5. -
Checked if the
3and5are present in thenumbersrange.
Use closed range to slice array
import Swiftvar 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 Swiftvar 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 Swiftif (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
5is present in the range using theifstatement.