Álvaro Medina Ballester

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

Posted July 28, 2014

author Álvaro Medina BallesterÁlvaro Medina Ballester is a mobile apps developer living in Palma, Spain. In ❤️ with React Native. Follow me on Twitter or Github.