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]
Sign up to request clarification or add additional context in comments.

Comments

3

For swift 3.0

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

Thats It!!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.