How to check if a range is empty in Swift

Overview

We can check if a range is empty in Swift by using the isEmpty property of a Range instance. It returns a boolean true or false indicating if the range is empty or not.

Syntax

range.isEmpty

Return value

The value returned is a boolean variable. If the range is empty, true is returned. Otherwise, it returns false.

Code

// create some ranges
let range1 = 1 ..< 6 // 1 to 5
let range2 = 10 ..< 50 // 10 to 49
let range3 = 0 ..< 0 // empty
let range4 = 3 ..< 3 // empty
// check ranges if they are empty
print(range1.isEmpty) // false
print(range2.isEmpty) // false
print(range3.isEmpty) // true
print(range4.isEmpty) // true

Explanation

  • Line 2–5: We create some ranges.
  • Line 8–11: We check if each range is empty using the isEmpty property. Then, we print the result to the console.

Free Resources