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.
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
).
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 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.
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
.
for
loopimport 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
.
if
conditionimport Swiftif (0...5).contains(5) {print(" 5 is present in the range 0...5")}
In the code above, we have:
0...5
.5
is present in the range using the if
statement.