|< When should you use switch statements rather than if?||Why does Swift use underscores with loops? >|
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: https://www.avanderlee.com/swift/ranges-explained/
SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.
Link copied to your pasteboard.