In Swift, we can create a range of values between two numeric values using the ...
range operator.
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
.
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 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 range5
is not present in the range because the half-open range doesn’t include the upper bound value.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.
for
loopimport 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
.
if
conditionimport 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:
0..<5
.if
statement to check if 5
is present in the range.5
is not present in the range, because in the half-open range 0..<5
the upper bound value 5
will be excluded.