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 Swiftlet numbers = 0..<5print("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 fromhalf-open range An interval of values from a lower bound to upper bound, excluding upper bound (in this case, 5) 1to5. Now thenumberswill contain the values of1,2,3,4. -
We checked if the
3and5are present in thenumbersrange.3is present in the range5is 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 Swiftvar 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 Swiftvar 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 Swiftif (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
ifstatement to check if5is present in the range. - We found that in our case,
5is not present in the range, because in the half-open range0..<5the upper bound value5will be excluded.