Check If A String Is A Palindrome In Swift
Code snippet for how to Check If A String Is A Palindrome In Swift with sample and detail explanation
A palindrome is a word, phrase, number, or other sequence of characters that read the same backward or forward, allowing for adjustments to punctuation and spaces. This article demonstrates how to check if a string is a palindrome using Swift programming language.
Code snippet: Check If A String is a Palindrome in Swift
Below is a simple function written in Swift that checks if a string is a palindrome:
func isPalindrome(_ s: String) -> Bool {
let normalizedString = s.lowercased().replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
let reversedString = String(normalizedString.reversed())
return normalizedString == reversedString
}
You can test the function with a string as follows:
let testString = "Madam, in Eden, I'm Adam"
print(isPalindrome(testString)) // Prints: true
Code Explanation: Check If A String is a Palindrome in Swift
Here is a step-by-step explanation of the code:
-
We define a function called
isPalindrome()
that accepts a string as input and returns a Boolean. -
Inside this function, we first normalize the string. The normalization process involves converting the string to lowercase letters using
.lowercased()
method and removing all non-alphanumeric characters by using.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
. The “\W” means any non-word character. As a result, we get a string that is easier to evaluate for palindrome. -
Next, we create a reversed version of the normalized string. We simply use Swift’s
.reversed()
method on the normalized string and then convert it back to a string. -
Finally, we compare the normalized string with its reversed counterpart using the equality operator (”==”). If they are the same, it means that the original string is a palindrome, so the function returns true. If not, the function returns false.
In the test example, the input string “Madam, in Eden, I’m Adam” returns true, showing that this string, ignoring punctuation, spaces, and case, is indeed a palindrome.
This function can help in various software development scenarios where string manipulation and evaluation is necessary.