Cheating on Swift Substrings

July 03, 2015

If you found yourself needing to get a substring of a String in Swift before you got around to the relavant chapter of the book you were probably left scratching your head for a bit. How could something so conceptually simple be so akward to perform?

Here’s a great article explaining how to find a substring in Swift, from Natasha The Robot.

It turns out that Swift Strings are much cooler than your old fashioned strings from other languages, and Swift Ranges are even cooler still. But unless you’re using them frequently, I find that

str.substringWithRange(Range(start: (advance(str.endIndex, -1)), end: str.endIndex))

doesn’t exactly roll off the tongue.

So here’s my cheat, which is to not use String at all. Arrays in Swift are super simple to chop up using plain integer ranges, and a String is just an Array<character>. Swift even lets you iterate over the contents of a String and access each Character in turn, but it doesnt give you String subscripting.

So theres a couple of cheat options, implement subscript on String yourself, or what I preferred, extend String to give you quick access to an Array representation of the String.

extension String {
    func asArray() -> [Character] {
        var array : [Character] = []
        for char in self {
        return array

You can then do fun stuff like this, which for me, reads very nicely.

let str = "Coma inducing corporate bollocks"
str.asArray().last // "s"
str.asArray()[10] // "i"
String(str.asArray()[2..<7]) // "ma in"

You don’t need to break out the big O notation to see this isn’t going to perform great, you’re iterating over the entire string everytime you want to get a piece of it, then the array methods are going to go do it again, so use with caution!