Manipulating strings comes up a lot in interview problems. Unfortunately, indexing strings in Swift isn’t so simple. Strings in Swift can be indexed using the String.Index type, but I would much prefer to use an Int.

I’ve come up with a couple solutions that will allow you to index strings with an Int. This code will not work in special cases, such as when the string contains special accents or emojis. This has to do with the way Swift treats strings inherently.

Currently, my favorite solution is to map the string to an array.

The upside is that it is simple and can be done quickly in an interview. The downside is the additional space required to create the array.

// String
let s = "ingax"

// String mapped to Array
let a = s.map { String($0) }

Another solution is to write a simple extension.

The downside of this solution is the time complexity. Each time we call a particular index with this method, we run through a loop. So if we could very easily write a program with a double loop.

extension String {
    subscript(_ i: Int) -> String {
        return String(self[index(startIndex, offsetBy: i)])
    }
}

Leave a Reply

Come See Me

San Francisco, CA
hello@ingax.com

See My Work