A filter is a question that you ask each and every object in an array. If the object answers true
to the question, it is copied to a new array!
Try this example in Playgrounds for fun.
print("Run this code in playgrounds.")
print("Add a few more 🧙🏾🪄🧙🏻🪄, and add more filters.")
print("=============================================")
struct Wizard {
let name: String // each student has a name
let house: House // each student belongs to a school house
// A wizard can only belong to one of these four houses
enum House {
case hufflepuff, griffendor, slytherin, ravenclaw
}
// Sample selection of wizards
static var wizards = [
Wizard(name: "Harry Potter", house: .griffendor ),
Wizard(name: "Luna Lovegood", house: .ravenclaw ),
Wizard(name: "Draco Malfoy", house: .slytherin ),
Wizard(name: "Albus Dumbledore", house: .ravenclaw ),
Wizard(name: "Ron Weasley", house: .griffendor ),
Wizard(name: "Delores Umbridge", house: .hufflepuff ),
Wizard(name: "Moaning Myrtle", house: .ravenclaw ),
Wizard(name: "Hermione Granger", house: .griffendor )
]
}
// Imagine asking all the students to stand in a line.
// Then you walk down the line asking each student, "Are you in House Griffendor?"
// If they answer "Yes", you add them to the griffendorWizards roster.
let griffendorWizards = Wizard.wizards.filter { $0.house == .griffendor }
// for each wizard in griffendor array, print their name
griffendorWizards.forEach { print($0.name) }
print("\(Wizard.House.griffendor) has \(griffendorWizards.count) students.")
Keep Coding!
You can create your own rules. It's up to your imagination, or your application's use case.
Please return here and let us know if you understand filters a bit better.