Use Range Operators in Swift
Written by Team Kodeco
Written by Team Kodeco
Swift provides two range operators that can be used to create ranges of values and check if a value falls within a range. The range operators in Swift are:
-
...
for closed range (includes the last value). -
..<
for half-open range (excludes the last value).
Here’s an example:
// Closed range: includes the last value)
for num in 1...3 {
print(num, terminator: " ")
}
// Output: 1 2 3
// Half-open range: excludes the last value
for num in 1..<3 {
print(num, terminator: " ")
}
// Output: 1 2
Checking if a Range Contains a Value
You can use contains
to check if a value falls within a range:
let a = 5
let range = 1...10
print(range.contains(a)) // true
print(range.contains(0)) // false
Prev chapter
4.
Use Ternary Conditional Operator in Swift
Next chapter
6.
Use Bitwise Operators in Swift