BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

One-sided ranges

Available from Swift 4.0

Paul Hudson      @twostraws

Last but not least, Swift 4 introduced Python-like one-sided collection slicing, where the missing side is automatically inferred to be the start or end of the collection. This has no effect on existing code because it's a new use for the existing operator, so you don't need to worry about potential breakage.

Here's an example:

let characters = ["Dr Horrible", "Captain Hammer", "Penny", "Bad Horse", "Moist"]
let bigParts = characters[..<3]
let smallParts = characters[3...]
print(bigParts)
print(smallParts)

That code will print out ["Dr Horrible", "Captain Hammer", "Penny"] then ["Bad Horse", "Moist"].

For more information see the Swift Evolution proposal for this new feature.

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Other changes in Swift 4.0…

Download all Swift 4.0 changes as a playground Link to Swift 4.0 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.