Reversed String

Reversing a string in Swift is done by using the reversed() method on its characters, then creating a new string out of the result. Here’s the code:

let str = "Hello, world!"
let reversed = String(str.reversed())
print(reversed)

Reverse a String without using reversed built-in function in Swift can be done using Swift higher order function. Complexity for this is O(n).

extension String {
    func reverse() -> String {
        return self.reduce("") { (reversed, newChar) -> String in
            return String(newChar) + reversed
        }
    }
}

tomkausch

Leave a Reply

Your email address will not be published. Required fields are marked *