iNick
iNick

Reputation: 115

Reversing strings in an array with Swift

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.

Upvotes: 3

Views: 3756

Answers (2)

guru
guru

Reputation: 2817

For swift 3.0

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

Thats It!!

Upvotes: 3

Ian
Ian

Reputation: 12768

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]

Upvotes: 7

Related Questions