Reversing a Swift String in Place


One of the interview questions at my old job we’d ask sometimes was to reverse a string in place; usually using C or Java. After conducting an interview one time, I decided to rewrite it in Swift. Here’s what I came up with:

func reverse(string: inout String) {
    var i = string.startIndex
    var j = string.index(before: string.endIndex)

    while i < j {
        let first = string[i]
        let second = string[j]

        string.remove(at: i)
        string.insert(second, at: i)
        string.remove(at: j)
        string.insert(first, at: j)

        i = string.index(after: i)
        j = string.index(before: j)

var str = "12345"
reverse(string: &str)

The Author

iOS and Mac developer.