Joseph Jude

Technology, Psychology, and Story Telling

Swift Challenge 002: Check if a string is palindrome

Posted: Tags: code,swift

Challenge: Write a program to check if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like "racecar"

Logic: Reverse the string and compare. If equal, then it is palindrome


print("Enter a string: ")
let userInput = readLine(stripNewline: true)!

let reverse = String(userInput.characters.reverse())

if (reverse == userInput) {
  print("\(userInput) is a palindrome") 
} else {
  print("\(userInput) is not a palindrome")


  • readLine reads input from console. It returns an optional string. Unwrap it with !
  • .characters gives characters in a string as an array
  • reverse() reverses the array (remember array is an ordered collection)

To Improve:

  • exit if no input given
  • be on continuous loop until ^D is pressed (more like a console app)


  • reading from console
  • strings as array of characters
  • string comparison

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.

Like the post? Retweet it. Got comments? Reply.


comments powered by Disqus