Home > database >  Swift Replace all special characters
Swift Replace all special characters

Time:09-22

How can I replace all charateres from a string to normal characteres

Example:

from:

cartões

To:

cartoes

another example:

from:

notificações

to:

notificacoes

CodePudding user response:

Swift has built in support for stripping diacritics/annotations from strings. This is primarily to support easy searching and comparisons but will solve your problem too. The API is

func folding( options: String.CompareOptions = [],
    locale: Locale?) -> String

If you will be using it regularly, the easiest way would be to create an extension on String with the required parameters preset:

extension String {
  func cleaned() -> Self {
    return self.folding(options: .diacriticInsensitive, locale: .current)
  }
}

which would let you do "notificações".cleaned() to return notificacoes

  • Related