From 932a0d224cadac16998af23e76912812289382af Mon Sep 17 00:00:00 2001 From: Ethan Willform <116986519+Ewill25@users.noreply.github.com> Date: Sun, 3 Dec 2023 14:52:50 -0800 Subject: [PATCH] Add files via upload Converted a version of the Palindrome Checker into Swift via xcode. --- PalindromeChecker/palindromeChecker.swift | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 PalindromeChecker/palindromeChecker.swift diff --git a/PalindromeChecker/palindromeChecker.swift b/PalindromeChecker/palindromeChecker.swift new file mode 100644 index 00000000..99d82136 --- /dev/null +++ b/PalindromeChecker/palindromeChecker.swift @@ -0,0 +1,45 @@ +import Foundation + +// Returns the first character of a string +func first(_ word: String) -> Character? { + return word.first +} + +// Returns the last character of a string +func last(_ word: String) -> Character? { + return word.last +} + +// Returns all but the first and last characters of a string +func middle(_ word: String) -> String { + guard word.count > 2 else { + return "" + } + return String(word.dropFirst().dropLast()) +} + +// Prints whether a word is a palindrome or not +func isPalindrome(_ word: String) { + if word.count <= 1 { + print("'\(word)' is a palindrome.") + return + } + if first(word) != last(word) { + print("'\(word)' is not a palindrome.") + return + } + isPalindrome(middle(word)) +} + +// Main function to handle user input +func main() { + print("Enter a word to check if it is a palindrome:") + if let word = readLine()?.trimmingCharacters(in: .whitespacesAndNewlines) { + isPalindrome(word) + } else { + print("Invalid input.") + } +} + +// Call the main function to start the program +main()