Using Swift’s Ranges
Open and half-open?
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
- You will be expected to be aware how to either make a Single View Application in Swift or use a Playground
- Ranges are zero-indexed in a similar fashion to Arrays
- The Integer type is referred to in this article, as are String types, so familiarity with these would be useful
- This article assumes some familiarity with collectiontypes in Swift
Keywords and Terminology
Range: The elements between the highest and lowest values
The Closed Range Operator
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.