Á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.


Álvaro Medina Ballester

Hi 👋! I'm Álvaro Medina Ballester, a mobile app developer living in Palma, Spain, focused on React, React Native, mobile design and user interfaces. Follow me on Twitter or Github.