Generics classes and inheritance

Viewed 156

I have the model object:

class Animal {
// ...
}

And subclasses:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

Also I've created the generic class

class AnimalController<T: Animal> {
      var animal: T? 
      func feed(animal: T) {
          let food = Food(T.self)
          animal.feed(food)
      }
}

Here it's the issue:

class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Error

        // I want control a cat
        self.controller = AnimalController<Cat>()  // Error
    }
}

How could I create generic class compatible with dogs and cats? Thanks!

UPDATED Hamish give me the solution linking other two posts.

I have the model object:

class Animal {
// ...
}

And subclasses:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

Also I've created the generic class

class AnimalController<T> {
    var type: T

    init(type: T) {
        self.type = type
    }

    func feed() {
        if type is Animal.Type {
            let food = Food(type as! Animal.Type)
            animal.feed(food)
        }
    }
}

Now it works:

class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Works!
        self.controller = AnimalController<Cat>()  // Works!
    }
}
3 Answers
Related