I am playing around with Swift and am stumbling over the following problem: given I have the predefined class Animal
:
//Predefined classes class Animal { var height: Float = 0.0 }
I now write the class Zoo
with the constructor accepting animals. But the Zoo
wants every animal to have a name and hence defines the Namable
protocol.
protocol Namable { var name: String {get} } class Zoo { var animals: Animal[] = []; }
How would you write an addAnimal
method that requires the object being passed as parameter to be both of type Animal
and conform to protocol Namable
? And how do you declare that for the animals
array?
func addAnimal:(animal: ????) { ... }
In Objective-C, I'd write something like this
- (void)addAnimal:(Animal<Namable>*)animal {...}
You can use a generic with a where
clause with multiple conditions.
func addAnimal<T: Animal where T: Nameable>(animal: T) { ... }
Amendment: You should probably make the whole class this generic so you can type the array properly
class Zoo<T: Animal where T: Nameable> { var animals : T[] = [] func addAnimal(a: T) { ... } }
To me, this seems more an architecture problem:
Nameable
is strange as a protocol. Logically, every Animal has the ability to be named so Animal
should always conform to Nameable
It would be much simpler to allow for nil
names when the animal is not named instead of having animals that can have a name and animals that can't.
Then you can enforce names in Zoo
simply by an assert
.
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