Search code examples
iosswiftunicodeuisearchbaruisearchcontroller

UISearchController does not recognise umlaut, Swift, iOS


I have a search function in my app but it does not recognise any umlaut (ä,ö,ü). I use UISearchController. How do I adjust the code that it recognises umlaut?

($0.title as AnyObject).contains(self.searchController.searchBar.text!.lowercased())

Solution

  • This works fine for me. I would sanity check your strings in lldb.

      func search() {
        let stringWithDiaeresis = "Reënter"
        let stringWithoutDiaeresis = "Reenter"
        let searchStringWithDiaeresis = "Reë"
        let searchStringWithoutDiaeresis = "Ree"
    
        if stringWithDiaeresis.contains(searchStringWithDiaeresis) {
          print("Range of Reë detected in Reënter")
        }
    
        if stringWithDiaeresis.contains(searchStringWithoutDiaeresis) {
          print("Range of Reë detected in Reenter")
        }
    
        if stringWithoutDiaeresis.contains(searchStringWithDiaeresis) {
          print("Range of Reë detected in Reenter")
        }
    
        if stringWithoutDiaeresis.contains(searchStringWithoutDiaeresis) {
          print("Range of Ree detected in Reenter")
        }
    
        /* Prints the following:
         Range of Reë detected in Reënter
         Range of Ree detected in Reenter
         */
    
        if (stringWithDiaeresis as AnyObject).contains(searchStringWithDiaeresis) {
          print("Reënter contains Reë")
        }
    
        if (stringWithDiaeresis as AnyObject).contains(searchStringWithoutDiaeresis) {
          print("Reënter contains Ree")
        }
    
        if (stringWithoutDiaeresis as AnyObject).contains(searchStringWithDiaeresis) {
          print("Reenter contains Reë")
        }
    
        if (stringWithoutDiaeresis as AnyObject).contains(searchStringWithoutDiaeresis) {
          print("Reenter contains Ree")
        }
    
        /* Prints the following:
         Reënter contains Reë
         Reenter contains Ree
         */
      }
    

    If your intention is to match strings with diacritics to those without, you're going to need to sanitize your data and remove diacritics from everything.

    E.g.

    if stringWithDiaeresis.localizedStandardContains(searchStringWithoutDiaeresis) {
      print("Reënter contains Ree")
    }
    
    /* Prints the following:
     Reënter contains Ree
     */
    

    The moral of the story here is that you really ought to be using the specialized/more sophisticated methods available to String types instead of generic contains().