# How do I solve the optional for palindrome exercise

hey there,
how do I solve this exercise using the stride method?
I have tried it ,but it is not working.
what did I do wrong?

``````var text = ["l","e","v","e","l"]
var reversed = [String]()

var counter = text.count - 1

for counter in stride(from: 4, to: 0, by: -1) {
reversed.append(text[counter])

}
if text == reversed {
print("we have a palindrome")
}else{
print("Look further")
}
``````

Hello @erikbusch5599231096, and welcome to the forums. I’m not really versed at all in Swift, but I just completed the exercise. `stride` generates a sequence which does not include the `to` value, so you have to make `to` one less than the end of the sequence you want. Also consider that you may want to make your code work with arrays of different lengths. How could you change the value given to `from` to account for an array of any size?

1 Like

Hi I think this can solve your problem.

var text:[String] = [“m”,“a”,“d”,“a”,“m”]

var reversed:[String] =

var counter:Int = text.count - 1

for counter in stride(from: counter , to: -1, by: -1) {
reversed.append(text[counter])
}

if text == reversed{
print(“We have a palindrome!”)
print("(reversed)")
} else {
print(“Is not a palindrome!”)
print("(reversed)")
}

1 Like

also…
HI! I was struggling too and played around with your code and with the array, instead of going to 0, I set it to -1, by :-1 and it worked.

var text = [“l”,“e”,“v”,“e”,“l”]
var reversed = String

var counter = text.count - 1

for counter in stride(from: 4, to: -1, by: -1) {
reversed.append(text[counter])

}
if text == reversed {
print(“we have a palindrome”)
}else{
print(“Look further”)
}

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.