so I have Animal superclass and three subclass : lion dog and elephant.
enum Gender {
case male
case female
}
class Animal {
var species: String
var gender: Gender
init (species: String, gender: Gender) {
self.species = species
self.gender = gender
}
}
// Lion Class
class Lion: Animal {
var age: Int = 10
init () {
super.init(species: "Lion", gender: Gender.male)
}
}
// Elephant Class
class Elephant: Animal {
var age: Int = 8
init () {
super.init(species: "Elephant", gender: Gender.female)
}
}
//Dog Class
class Dog: Animal {
var age: Int = 6
init () {
super.init(species: "Dog", gender: Gender.female)
}
}
They all have gender variable which is inherited from superclass Animal.
Now I want to have a computed property: maleAnimal of type [Animal] which contains all male animal, what is the best way to do it ?
class Zoo {
var animals: [Animal] = [Lion(), Elephant(), Dog()]
var maleAnimals: [Animal] {
for animalClasses in animals {
if animalClasses.gender == Gender.male {
return self.maleAnimals.append(animalClasses)
}
}
}
}
I have tried some thing like the example beneath but it apparently does not work.
Any hints are appreciated!
You can use the filter method on arrays.
var maleAnimals : [Animal] {
return animals.filter { $0.gender == .male }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With