Search code examples
arraysswiftfiltercontains

Filter an array of objects by property, using an array of values in Swift


What is the most efficient way of filtering an array of objects based on one of their properties, using an array of values? I could iterate through the items, but I can't help thinking there's a really efficient way using Array.filter and Array.contains - I'm just not proficient enough with Swift to be able to put the pieces together.

For example, if I have an array containing Book objects, each of which has a String author property, how would I filter it to show only books by John Smith, Arthur Price or David Jones?

Something along the lines of:

Class Book {
    var author : String = String()
}

var books : Array = [Book]()
//books added elsewhere

let authors = ["John Smith", "Arthur Price", "David Jones"]

let filteredBooks = books.filter({authors.contains({($0 as Book).author})})

Solution

  • I'd recommend you make an index of books by author:

    let book = Book(author: "Arsen")
    let bookIndex = [book.author: [book]]
    

    And now you have incredible fast access to your book filtered by author:

    bookIndex["Arsen"] // => [Books]
    

    For multiple authors:

    var results = [Book]()
    for author in authors {
        if let books = bookIndex[author] {
            results += books
        }
    }
    
    results