July 27, 2014 · 1 min read

Using ranges in strings with Swift

Swift is still under development, so there are a lot of things to be done from the Apple team. One of these 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.

Tags:
Hi 👋! I’m Álvaro, a software engineer and manager living in Palma, Spain. My current focus is on the intersection of engineering, product development and management. Learn more about me.
© 2020 - present.