C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
While: We loop over the string with a while-loop. This is needed because we must avoid calling predecessor() on startIndex.
WhileIf: This logic ensures we do not call predecessor on startIndex. We terminate the loop once startIndex has been reached.
Append: We append characters to the Character array with append. We finally return a string based on these new characters.
Swift program that uses reverse extension method
extension String {
    func reverse() -> String {
        let data = self
        var array = [Character]()
        // Begin at endIndex.
        var i = data.endIndex
        // Loop over all string characters.
        while (i != data.startIndex) {
            // Get previous index if not on first.
            if i > data.startIndex {
                i = i.predecessor()
            }
            // Add character to array.
            array.append(data[i])
        }
        // Return reversed string.
        return String(array)
    }
}
// Test string reversal extension method.
var animal = "bird"
let result = animal.reverse()
print(result)
var plant = "carrot"
let result2 = plant.reverse()
print(result2)
Output
drib
torrac