1

I am currently recording the discovery preference of a User (see image below) and would like to filter the list of Users being displayed in a CollectionView that meet the discovery preferences set by the User.

enter image description here

Every User in the array has a birthYear, gender and discoverable Bool.

This is my function which currently works for only the discoverable Bool and displays only User's which are set to true.

How do I chain the filter conditions that I need in order to only display those Users that meet the discovery preferences of a User above?

    func discoverUsers(location: CLLocation) {

        DataService.run.getUsersAtVenue(forVenueLocation: location, forUid: (Auth.auth().currentUser?.uid)!) { (users, success) in

            if success {
                self.users = users

                self.filteredUsers = self.users.filter({ (user: User) -> Bool in
                    return user.discoverable == true

                    //-> Chain filter conditions to check for here: gender, age
                })

                self.collectionView.reloadData()
                Utilities.run.dismissSVHUD(delay: 0.5)

            }//end if

        }//end closure

    }//end func


}//end class

1 Answer 1

2

I am having a hard time understanding precisely what you want to achieve in particular. However, here is how the filter function plays out:

Given that users is an array of elements of type:

struct User {
    let age: Int
    let isMale: Bool
    // ...
}

You can filter like so:

filteredUsers = users.filter { user in
     return (user.age <= maxAge && user.age >= minAge) && /* include any other condition you need */ 
}
Sign up to request clarification or add additional context in comments.

2 Comments

yeah this actually helped...I'm still a beginner and didn't realise that you can simply bind the filter condition one after another in the way you have shown.
Alright I am really glad it helped! Try to do more research by your own as you gain expertise as a "How to use the filter function in swift" Google search or a quick look at apple's book on swift would be enough to answer your question for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.