xxFlashxx
xxFlashxx

Reputation: 271

Swift filtering custom objects in an array

I would like to know if there are any efficient ways to filter an array of custom object like the one i have below. I have a class of Author and a class of Book that can have multiple authors with different properties such as enum for state of the book, comments on the book written by the author and an array in which the state of the book had changed. I would like to filter by different state, author, and dates to and from where all 4 parameters are optionals.

class Author : Equatable {
   let name : String
   let id = UUID()
}

class Book : Equatable {
   let date = Date()
   var comments : [Comment] = []
   var writtenBy : [Author] = []
   var state : State = .available {
       didSet {
            updateState(timestamp: Date())
        }
    }
}

enum State : String, CaseIterable {
    case available
    case unavailable
    case missing
}


class CollectionOfBooks {
    private static var arrayOfBooks : [Book] = []

    static func getAllBooks(state: State?, authorId: UUID?, fromDate: Date?, toDate : Date?) -> [Book] {


    let filteredArray = arrayOfBooks.filter({$0.state == state})
    filteredArray = arrayOfBooks.filter....
    filteredArray = arrayOfBooks.filter....
    filteredArray = arrayOfBooks.filter....

return filtered array 

 // what is the most efficient way of sorting the my array? 
//At the moment i only know how to achieve this by filtering one parameter at a time. 
    }
}

Upvotes: 0

Views: 3673

Answers (1)

Shamas S
Shamas S

Reputation: 7549

You can just concat all your conditions inside that one conditional.

let filteredArray = arrayOfBooks.filter({$0.state == state && $0.name.contains("asdf")})

Upvotes: 3

Related Questions