Search code examples
swiftsearchswift3

swift 3 - search result also with diacritics


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 diacritics. Example: Enter a search holesovice, I need to find holesovice and also holešovice.

Here is part of my code:

func filterContentForSearchText(_ searchText: String) {
        filteredERequests = requests.filter({( request : CityRequest) -> Bool in

            return request.cityName.lowercased().contains(searchText.lowercased())

        })
        myTable.reloadData()
    }

Solution

  • 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"]