Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
range
empty
communitycreator

How to check if a range is empty in Swift

Theodore Kelechukwu Onyejiaku

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
Check if some ranges are empty in Swift

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.

RELATED TAGS

swift
range
empty
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring