< When should you use switch statements rather than if? | Why does Swift use underscores with loops? > |
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:
print(names[0])
With ranges, we can also print a range of values like this:
print(names[1...3])
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:
print(names[1...])
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: https://www.avanderlee.com/swift/ranges-explained/
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!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.