NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
Quick Tip Icon
Quick Tip

User-level string search in Swift

When implementing search functionality in Swift apps, it’s important to make sure it behaves in a way users expect. Typically, when users search within apps or the system, they expect loose matches that ignore case and accents. For this reason, instead of using strict checks like range(of:) or contains(), it’s better to use flexible, locale-aware methods.

In Swift, localizedStandardRange(of:) is the most appropriate method for performing user-level string searches, as it mirrors how searches are done generally in the system. It’s case-insensitive, diacritic-insensitive, and adjusts to the user’s locale settings, ensuring that results meet user expectations.

Here’s an example with German strings:

import Foundation

let germanStrings = ["STRASSE", "Straße", "straße"]
let searchStr = "strasse"

for str in germanStrings {
    if let rangeOfMatch = str.localizedStandardRange(of: searchStr) {
        print(str[rangeOfMatch])
    }
}

This will print STRASSE, Straße, and straße, as they are all considered equivalent in German.

Note that localizedStandardRange(of:) comes from the Foundation framework, so we'll need to import Foundation when using it.


To illustrate diacritic insensitivity, here’s a French example:

import Foundation

let frenchStrings = ["fête", "Fete", "FÊTE"]
let searchStr = "fete"

for str in frenchStrings {
    if let rangeOfMatch = str.localizedStandardRange(of: searchStr) {
        print(str[rangeOfMatch])
    }
}

This example will print all variants of "fête", illustrating that the search is accent-insensitive.

Use localizedStandardRange(of:) to provide users with a search experience that feels familiar and intuitive, just like in other system-wide searches.


If you're an experienced Swift developer looking to level up your skills, take a look at my book Swift Gems. It offers 100+ advanced Swift tips, from optimizing collections and leveraging generics, to async patterns, powerful debugging techniques, and more - each designed to make your code clearer, faster, and easier to maintain.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35