Reputation: 1647
I have a problem filtering my array of elements, let's say.
Box
-[Zombies]
-[Players]
-[Weapons]
I have a bunch of boxes which can contain all of the arrays listed above.
[Box]
Now I want to filter out the boxes that have whatever I want to filter out. If I choose a specific zombieId + playerId, I will only get the boxes with those etc.
I tried using something like:
let filteredBoxes = boxes.filter { (box) -> Bool in
selectedZombies.contains(where: { $0.zombieId == box.zombies.zombieId })
&&
selectedPlayers.contains(where: { $0.playerId == box.players.playerId })
&&
selectedWeapons.contains(where: { $0.weaponId == box.weapons.weaponId })
}
This works, but requires the user to select all 3 filters before anything is shown.
I also want to show the boxes that matches the users selection even if they only select some filters for i.e. selected zombies.
Upvotes: 0
Views: 69
Reputation: 72440
If you want to filter the specific condition you can make it like this, declare 3 instance property of type Bool
to control which filter user currently allow and use it with filter
.
var filterZombie = true
var filterPlayer = true
var filterWeapon = false
//So now filterZombie and filterPlayer is true you want to filter only these two condition so make filter like this
let filterArray = boxes.filter { (box) -> Bool in
let zombieResult = filterZombie ? selectedZombies.contains(where: { $0.zombieId == box.zombies.zombieId }) : true //Set default result as true
let playerResult = filterPlayer ? selectedPlayers.contains(where: { $0.playerId == box.players.playerId }) : true //Set default result as true
let weaponResult = filterWeapon ? selectedWeapons.contains(where: { $0.weaponId == box.weapons.weaponId }) : true //Set default result as true
return zombieResult && playerResult && weaponResult
}
Upvotes: 2