gpt4 book ai didi

swift - 泛型类和继承

转载 作者:搜寻专家 更新时间:2023-10-31 23:09:43 32 4
gpt4 key购买 nike

我有模型对象:

class Animal {
// ...
}

和子类:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

我还创建了泛型类

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

问题来了:

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
}
}

如何创建与狗和猫兼容的通用类?谢谢!

已更新 Hamish 给我链接其他两个帖子的解决方案。

我有模型对象:

class Animal {
// ...
}

和子类:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

我还创建了泛型类

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

现在可以了:

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!
}
}

最佳答案

Swift 是一种强类型语言。你已经声明了你的属性 controller,你不能改变它的类型,但这完全没问题,因为 Swift 支持泛化范式,它允许你将对象保存在一个具有通用属性的属性中父类(super class)。

关于swift - 泛型类和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44354158/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com