Require type and protocol for method parameter

cocoa, ios, protocols, swift, xcode

Solution

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) {
        ...
    }
}

Problem

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 {...} ```

Original source