Jio M. Jio M. - 3 months ago 54
Swift Question

Reverse Strings without using predefined functions

Pardon me as I am a newbie on this language.

Edit: Is there a way to reverse the position of a array element?

I am trying to create a function that test the given input if its a palindrome or not. I'm trying to avoid using functions using reversed()

let word = ["T","E","S","T"]
var temp = [String]()
let index_count = 3

for words in word{
var text:String = words
print(text)
temp.insert(text, atIndex:index_count)
index_count = index_count - 1
}

Answer

Your approach can be used to reverse an array. But you have to insert each element of the original array at the start position of the destination array (moving the other elements to the end):

// Swift 2.2:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
    reversed.insert(char, atIndex: 0)
}
print(reversed) // ["T", "S", "E", "T"]

// Swift 3:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
    reversed.insert(char, at: 0)
}
print(reversed) // ["T", "S", "E", "T"]

The same can be done on the characters of a string directly:

// Swift 2.2:
let word = "TEST"
var reversed = ""
for char in word.characters {
    reversed.insert(char, atIndex: reversed.startIndex)
}
print(reversed) // "TSET"

// Swift 3:
let word = "TEST"
var reversed = ""
for char in word.characters {
    reversed.insert(char, at: reversed.startIndex)
}
print(reversed)