3

I am looking to reverse an array of strings. For example the original array would look like this

var array = ["lizard", "Rhino", "Monkey"]

and the end result should be those words reversed in the same order like this remaining in one array:

["drazil", "onihR", "yeknoM"]

what I have now is this and I am reversing the strings correctly however it is making 3 separate arrays and all of the strings are separated by commas.

var array = ["lizard", "Rhino", "Monkey"]

for index in (array) {
  println(reverse(index))
}

[d, r, a, z, i, l]
[o, n, i, h, R]
[y, e, k, n, o, M]

any help would be appreciated thank you.

2 Answers 2

7

A shorter way is to map the array of strings and reverse the characters and then initialize a String from them.

Swift 2.0:

let array = ["lizard", "Rhino", "Monkey"]
let reversed = array.map() { String($0.characters.reverse()) }
print(reversed) // [drazil, onihR, yeknoM]

Swift 1.2:

let array = ["lizard", "Rhino", "Monkey"]
let reversed = array.map() { String(reverse($0)) }
print(reversed) // [drazil, onihR, yeknoM]
0
3

For swift 3.0

func reverseAString(value :String) -> String {
    //value
    return  (String(value.characters.reversed()))
}

Thats It!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.