How to remove diacritics from a String in Swift?

后端 未结 4 2027
醉话见心
醉话见心 2020-12-01 01:32

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

相关标签:
4条回答
  • 2020-12-01 01:33

    This is my solutión

    Swift 5

        extension String {
    
            func unaccent() -> String {
    
                return self.folding(options: .diacriticInsensitive, locale: .current)
    
            }
    
        }
    
    0 讨论(0)
  • 2020-12-01 01:34

    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"
    
    0 讨论(0)
  • 2020-12-01 01:41

    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
    
    0 讨论(0)
  • 2020-12-01 01:47

    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()

    0 讨论(0)
提交回复
热议问题