Comparing strings, ignoring case, punctuation, and whitespace I have built a search function that will compare strings regardless of punctuation and whitespace. It is case insensitive.

Here is my current function:

var itemsToFilter = MPMediaQuery.songs().items!

func searchForItemsWithString(_ searchText: String) {
    if searchText != "" {
            let filteredItems = itemsToFilter.filter { item in
                let filterStr = item.title

                if filterStr == nil {
                    return false
                }

                let punctuation = CharacterSet.punctuationCharacters
                let whitespace = CharacterSet.whitespaces
                let unwanted = punctuation.union(whitespace)
                let filterStringContainsSearchText = filterStr!.components(separatedBy: unwanted).joined(separator: " ")

                return filterStringContainsSearchText.contains(searchText)
            }

    }
}


This works, but it is very slow. How can I optimise it?

What else can I improve?
You might want to create a combined CharacterSet of punctuation and whitespace first and then apply this set using a single operation. This should speed things up. Please have a look at this code snippet:

let punctuation = CharacterSet.punctuationCharacters
let whitespace = CharacterSet.whitespaces
let unwanted = punctuation.union(whitespace)
let components = filterString.components(separatedBy: unwanted).joined(" ")
let filterStringContainsSearchText = components.contains(searchText)