How to remove diacritics (or accents) from a String
(like say change \"één\" to \"een\") in Swift? Do I have to go back to NSString
or can it be do
This is my solutión
Swift 5
extension String {
func unaccent() -> String {
return self.folding(options: .diacriticInsensitive, locale: .current)
}
}
Update to @MartinR's answer… a Swift 3 extension to provide a string for sorting / searching, that might be useful for someone…
extension String {
var forSorting: String {
let simple = folding(options: [.diacriticInsensitive, .widthInsensitive, .caseInsensitive], locale: nil)
let nonAlphaNumeric = CharacterSet.alphanumerics.inverted
return simple.components(separatedBy: nonAlphaNumeric).joined(separator: "")
}
}
e.g.
print("Mÿ nâMe ís jÄço´B".forSorting) // "mynameisjacob"
You can operate directly on a Swift String
(if "Foundation" is imported):
let foo = "één"
let bar = foo.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
print(bar) // een
Swift 3:
let foo = "één"
let bar = foo.folding(options: .diacriticInsensitive, locale: .current)
print(bar) // een
Answer update for Swift 5.0.1
func toNoSmartQuotes() -> String {
let userInput: String = self
return userInput.folding(options: .diacriticInsensitive, locale: .current)
}
and use it someTextField.text.toNoSmartQuotes()