swift 3 - search result also with diacritics

后端 未结 2 1345
别那么骄傲
别那么骄傲 2020-12-20 02:59

In my application I use a search that works well but I need advice. I do not know how to do that when I search for text without diacritics that the result also with diacriti

相关标签:
2条回答
  • 2020-12-20 03:40

    This is Martin R's solution, just easier to consume.

    Copy this into a Swift file:

    extension String {
        func contains(insensitive other: String, range: Range<String.Index>? = nil, locale: Locale? = nil) -> Bool {
            return self.range(of: other, options: [.diacriticInsensitive, .caseInsensitive], range: range, locale: locale) != nil
        }
    }
    

    Use it like this:

    if "Música".contains(insensitive: "music") {
        print("hurray!")
    }
    
    0 讨论(0)
  • 2020-12-20 03:44

    You can use range(of:, options:) with options for a diacritic insensitive (and optionally case insensitive) search. Example:

    let list = ["holesovice", "holešovice"]
    let searchTerm = "sovi"
    
    let filtered = list.filter {
        $0.range(of: searchTerm, options: [.diacriticInsensitive, .caseInsensitive]) != nil
    }
    
    print(filtered) // ["holesovice", "holešovice"]
    
    0 讨论(0)
提交回复
热议问题