Skip to content

Instantly share code, notes, and snippets.

@amfathi
Last active April 21, 2020 08:08
Show Gist options
  • Select an option

  • Save amfathi/487e2642f197f71c00d6d5748dbfc8a1 to your computer and use it in GitHub Desktop.

Select an option

Save amfathi/487e2642f197f71c00d6d5748dbfc8a1 to your computer and use it in GitHub Desktop.
Basic reversing algorithms for arrays and strings.
import Foundation
// MARK: - Reverse Array
func reverse<T>(array: [T]) -> [T] {
var reversedArray = array
var index = 0
while index < array.count {
reversedArray[index] = array[array.count - index - 1]
index += 1
}
return reversedArray
}
reverse(array: [1, 2, 3, 4, 5]) // -> [5, 4, 3, 2, 1]
reverse(array: ["1", "2", "3", "4", "5"]) // -> ["5", "4", "3", "2", "1"]
reverse(array: [true, false, false]) // -> [false, false, true]
// MARK: - Reverse String
func reverse(string: String) -> String {
var reversedString = ""
for char in string {
reversedString = String(char) + reversedString
}
return reversedString
}
reverse(string: "Ahmed Fathi") // -> "ihtaF demhA"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment