Search code examples
arraysswift

Searching for part of a String within an Array


The below code works well to filter books by author but only works when search string is equal to full string. Example where authors contains full names, e.g. ["Jack Nicklaus", "Arnold Palmer", "Sam Snead"]

How do I allow search bar to filter based on part of name and not case sensitive, example "Nicklaus"

var filteredBooksByAuthor: [Book] {
    if searchTextAuthor.isEmpty {
        books
    } else {
        books.filter { $0.authors.contains(searchTextAuthor) }
    }
}

Solution

  • You could reduce the authors of a book and filter on that.

    import Foundation
    
    let searchTextAuthor = "PalmER"
    let filteredBooks: [Book]
    
    if searchTextAuthor.isEmpty {
        filteredBooks = books
    } else {
        filteredBooks = books.filter { b in
            b.authors.reduce("") { partialResult, author in
                partialResult + " \(author)"
            }.localizedCaseInsensitiveContains(searchTextAuthor)
        }
    }