Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require type and protocol for method parameter

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 {...} 
like image 992
cschwarz Avatar asked Jun 15 '14 16:06

cschwarz


2 Answers

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) {         ...     } } 
like image 62
Kevin Avatar answered Sep 21 '22 12:09

Kevin


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.

like image 43
Sulthan Avatar answered Sep 18 '22 12:09

Sulthan