How to remove diacritics from a String in Swift?

Solution 1:

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

Solution 2:

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"

Solution 3:

This is my solutión

Swift 5

    extension String {

        func unaccent() -> String {

            return self.folding(options: .diacriticInsensitive, locale: .current)

        }

    }

Solution 4:

This can also be done applying a StringTransform:

let foo = "één"
let bar = foo.applyingTransform(.stripDiacritics, reverse: false)!
print(bar) // een

Or implementing a custom property to StringProtocol

extension StringProtocol {
    var stripingDiacritics: String {
        applyingTransform(.stripDiacritics, reverse: false)!
    }
}

let bar = foo.stripingDiacritics
print(bar) // een