Using Swift’s Ranges

Image by Silas Baisch @silasbaisch

Before we start

Ranges are extremely useful when you produce Swift applications as they allow you to select a range (that is, a subset of an existing) type.

Difficulty: Beginner | Easy | Normal | Challenging This article has been developed using Xcode 12.1, and Swift 5.3


Keywords and Terminology

Range: The elements between the highest and lowest values

Swift Ranges

The Closed Range Operator

A ClosedRange is declared by using the ... operator between two Int Integer types, where we can think of the first Int as the lowerBound, and the second as the upperBound. The range includes the upper bound.

This can be used to see whether a value is contained within this particular range of values

This range can then be used to iterate over a collection, for example a collection of Strings (in this case an Array, which is storying the names of some people

** Note** Because a closed range includes its upper bound, a closed range whose lower bound is equal to the upper bound contains that value so by definition so the following is true

The Half Open Range Operator

This is similar to the Closed Range Operator, as a half-open range. The range excludes the upper bound.

The one-sided operator

A one-sided operator only has the lower bound. Effectively this means “move as far as possible in the direction of the operator”.


I hope you have enjoyed reading this tutorial.

It has covered The Closed Range Operator, The Half Open Range Operator and The one-sided operator. This is useful when we write our code for all sorts of uses! I hope it certainly has been useful for you..!

The Repo has some files that you might find useful to download at your leisure.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store