NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

Why does Swift have two range operators?

Paul Hudson    @twostraws   

Updated for Xcode 13.3

When we think about ranges of values, English is quite confusing. If I say “give me the sales figures up to yesterday” does that mean including yesterday or excluding yesterday? Both are useful in their own right, so Swift gives us a way of representing them both: ..< is the half-open range that specifies “up to but excluding” and ... is the closed range operator that specifies “up to and including”.

To make the distinction easier when talking, Swift regularly uses very specific language: “1 to 5” means 1, 2, 3, and 4, but “1 through 5” means 1, 2, 3, 4, and 5. If you remember, Swift’s arrays start at index 0, which means an array containing three items have items at indexes 0, 1, and 2 – a perfect use case for the half-open range operator.

Things get more interesting when you want only part of a range, such as “anything from 0 upwards” or “index 5 to the end of the array.” You see, these are fairly useful in programming, so Swift make them easier to create by letting us specify only part of a range.

For example, if we had an array of names like this one:

let names = ["Piper", "Alex", "Suzanne", "Gloria"]

We could read out an individual name like this:


With ranges, we can also print a range of values like this:


That carries a small risk, though: if our array didn’t contain at least four items then 1...3 would fail. Fortunately, we can use a one-sided range to say “give me 1 to the end of the array”, like this:


So, ranges are great for counting through specific values, but they are also helpful for reading groups of items from arrays.

If you’d like to keep learning more about ranges in Swift, you should check out Antoine van der Lee’s article on the topic:

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.9/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.