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 learn advanced techniques, check out my latest book Swift Gems. It’s packed with tips and tricks focused solely on the Swift language and Swift Standard Library. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice that will elevate your Swift development skills to the next level. Grab your copy and let's explore these advanced techniques together.