Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ["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"

        if searchTextAuthor.isEmpty {
           books
        } else {
            books.filter { $0.authors.contains(searchTextAuthor) }
        }
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading