Search code examples
swiftstringpalindrome

How to check a string is symmetric or not in Swift


return value == String(value.reversed())

This is what I tried. It works well but takes a little bit longer. Does anyone know a better way?


Solution

  • There is nothing available in the standard library for String, or for anything else, so a solution for only String probably isn't the best option.

    You don't need to make a new instance of anything based on reversed; elementsEqual does the job.

    public extension Sequence where Element: Equatable {
      var isSymmetric: Bool { elementsEqual(reversed()) }
    }
    
    "🐈🐆🐅🐆🐈".isSymmetric // true
    "🐈🐆🐅".isSymmetric // false