Swift Range or ClosedRange

What is a Swift Range and how to create?

Tested on: Xcode 12.2, Swift 5.3

Range or ClosedRange able you to generate a sequence of countable integers or float. This is like an array of integers or float. For example, if you want to create an array of value such as 0, 1, 2, 3, 4, 5. Instead of typing it out one at a time. You can use to range to generate for you.

Topics:

  1. How to create a Range?
  2. Inspecting a Range





1. Creating a Range

1.1 Closed Range

You can create a closed range by using (...).

For example, 0...5 will produce a value from 0 to 5 inclusive.

Swift Code :

let rangeInt = 0...5
let rangeDouble = 0.0...1.1

1.2 Half-open Range

You can replace the three dots with two dots plus a less than sign (<). Half-open means that the range goes from the first value to the last one but not including.

For example, 0...5 will produce value from 0 to 5 but not including 5.

Swift Code :

let rangeInt = 0..<5
let rangeDouble = 0.0..<1.1

Both open and half-open ranges must be increasing and the second number must always be greater than the first value.




2. Inspecting a Range

You can inspect the range to get information about it such as finding the number of value by using count, finding the lower and upper bound. The code below is the range that we will be using to inspect.

Swift Code :

let rangeInt = 0..<5

.count

Swift Code :

print(rangeInt.count)

Output :

5


.lowerBound

Swift Code :

print(rangeInt.lowerBound)

Output :

0


.upperBound

Swift Code :

print(rangeInt.upperBound)

Output :

5