In this tutorial you will learn about the Swift Ranges and its application with practical example.
Swift Ranges
Range is a collection of consecutive or sequential values, defined by its lower and upper bound. Elements in ranges can be of both the element type and the index type in the collection.
Example:-
1 |
0,1,2,3,4,5,6,7,8,9 |
In Swift, ranges can be created with two range operators as following –
Half Open Range Operator (lowerBound..<upperBound)
The ranges created with half-open range operator included all the consecutive values in the interval except its upperBound value. Half open range can be declared using ..< operator as following –
Syntax:-
1 |
lowerBound..<upperBound |
Example:-
1 2 |
// 0 to 9, 10 is not included let oneDigitNums = 0..<10 |
Closed Range Operator (lowerBound…upperBound)
The ranges created with closed range operator included all the consecutive values in the interval include its lowerBound and upperBound values. Closed range can be declared using …(3 dots)operator as following –
Syntax:-
1 |
lowerBound...upperBound |
Example:-
1 2 |
// 0 to 10 , including 0 and 10 itself let nums = 0...10 |