Trim a String in Swift

I needed to trim whitespace from some user input in a Swift app I'm working on. I could have used the ability to bridge to NSString and called stringByTrimmingCharactersInSet: but doing it in Swift seemed like a fun little exercise.

let whitespaceAndNewlineChars: [Character] = ["\n", "\r", "\t", " "]

extension String {
    func rtrim() -> String {
        if isEmpty { return "" }
        var i = endIndex
        while i >= startIndex {
            i = i.predecessor()
            let c = self[i]
            if find(whitespaceAndNewlineChars, c) == nil {
                break
            }
        }
        return self[startIndex...i]
    }

    func ltrim() -> String {
        if isEmpty { return "" }
        var i = startIndex
        while i < endIndex {
            let c = self[i]
            if find(whitespaceAndNewlineChars, c) == nil {
                break
            }
            i = i.successor()
        }
        return self[i..<endIndex]
    }

    func trim() -> String {
        return ltrim().rtrim()
    }
}

Update: @ChromophoreApp on Twitter pointed out that if you use subscripting instead of substringFromIndex you can avoid importing Foundation at all. What can I say? Old habits die hard. Thanks!

Download this code as a playground.

"Trim a String in Swift" was originally published on 21 Apr 2015.