Álvaro Medina Ballester

Using ranges in strings with Swift

July 27, 2014

Swift is still under development, so there are a lot of things to be done from the Apple team. One of this things is the use of ranges in the String type. One would expect to create a substring this way:

let substring = string.substringWithRange(2..5)

But unfortunately, this doesn’t work. There’s even a rdar filled for that. If we can use ranges using the two or three dot notation, it would be very nice to do it to create substrings. In the meantime, we can use the existing NSString’s methods:

let string = "string" as NSString
let substring = string.substringWithRange(NSMakeRange(2, 5))

In this SO question you can find more ways to use ranges in String’s.


Hi 👋! I’m Álvaro, a software engineer living in Palma, Spain. My current focus is on the intersection of mobile, front-end engineering, design and product development.

I have worked for startups and big companies, helping them envision their mobile strategy. Currently, I serve as a Mobile Tech Lead at APSL.net. Learn more about me.

The header image is a simulation of material orbiting close to a Black Hole. Original. Credits: ESO/Gravity Consortium/L. Calçada.