How To Find A Substring In Range of a Swift String

Swift Ranges are wildly different than NSRange in Objective-C. I therefore find myself always spending way more time working with Swift Ranges than I ever think I would! Of course, in retrospect, Swift Ranges make a lot of sense, but they’re hard to work with out of the box.

As a demo, here is how you get a substring at a specific start and end point:

var str = "Hello, playground"

let rangeOfHello = Range(start: str.startIndex,
                         end: advance(str.startIndex, 5))
let helloStr = str.substringWithRange(rangeOfHello)
helloStr //"Hello"

As you can see, you can’t just specify a range with Ints! You need to use the String’s startIndex and endIndex properties (of type String.Index not Int), to work specifically with ranges.

To get a range beyond the startIndex, you can use the advance function as demoed above. You can also advance in the negative direction, so if you need to get the index in relation to the endIndex, just use a negative value as follows:

let dob = "01/01/2000"

let rangeOfYear = Range(start: (advance(dob.endIndex, -4)),
                        end: dob.endIndex)
let yearStr = dob.substringWithRange(rangeOfYear)
yearStr // "2000"

Again, in retrospect, I find Swift Ranges to be very clean and elegant. Just have to remember how to use them every time!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.