How to create a range in Swift
Overview
A range is an interval of number values that has a starting point of, but does not include, the upper point. For example, the range of 1–5 is 1, 2, 3, 4.
We can create a Range instance in Swift using the half-open range operator (..<).
Syntax
variable = lowerbound ..< upperbound
Parameters
lowerbound: This is the lowest range value.upperbound: This is the limit of the range but is not included as part of the range.
Return value
A range is returned.
Code example
// create some rangeslet range1 = 0 ..< 5let range2 = 0 ..< 0 // empty range// print values in the rangefor value in range1 {print(value)}// print values in empty rangefor value in range2 {print(value) // nothing is printed}
Explanation
- Line 2–3: We created some ranges using the half-open range operator (
..<). One of them is empty and the other is not. - Line 6–11: We used the
for-inloop to loop through the ranges and printed to the console.