NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Why does Swift have two range operators?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

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

Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.