Swift Ranges

Ramesh Chavan
2 min readOct 3, 2022

--

In Swift, a range is a series of values between two numeric intervals.

Swift Ranges
  • ... is a range operator
  • 1...4 contains values 1, 2, 3, 4
  • 1 is lower bound (first element)
  • 4 is upper bound (last element)

Types of Range in Swift

1. Closed Range

A closed range includes all the values in the interval from the lower bound to the upper bound.

It is declared using the ... (3 dots) operator. For example,

// 1...4 is close range
for numbers in 1...4 {
print(numbers)
}

Output

1
2
3
4

2. Half-Open Range

A half-open range includes all the values from the lower bound to the upper bound. However, it excludes the upper bound (last number).

It is declared using the ..< operator.

for numbers in 1..<4 {
print(numbers)
}

Output

1
2
3

3. One-sided Range

We can create a one-sided range using either of the ... or the ..< operator.

A one-sided range contains elements up to infinite in one direction.

let range1 = ..<2

Here, ...<2 is a one-sided range. It contains all elements from 2 to -∞. Similarly, the range

let range2 = 2...

contains all elements from 2 to +∞.

We can verify this by checking if a certain number is present in the range. For example,

// one-sided range using 
// ..< operator
let range1 = ..<2

// check if -9 is in the range
print(range1.contains(-1))

// one-sided range using
// ... operator
let range2 = 2...

// check if 33 is in the range
print(range2.contains(33))

Output

true
true

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ramesh Chavan
Ramesh Chavan

Written by Ramesh Chavan

Like to work on iOS, Android, UIPath and Graph DB

No responses yet

Write a response