gpt4 book ai didi

ios - Swift 中的多个泛型类继承

转载 作者:行者123 更新时间:2023-11-28 11:14:05 38 4
gpt4 key购买 nike

假设我有一个模型和一个基本模型:

class BaseModel: NSObject {
var name = ""
}

class Model: BaseModel {
var desc = "abc"
}

我添加了一个服务来处理这些模型:

class AbstractService<T: NSObject>: NSObject {
var items = [T]()
}

class BaseModelService<T: BaseModel>: AbstractService<BaseModel> {
}

class ModelService<T: Model>: BaseModelService<Model> {
}

现在我想从 ModelService 访问 items 变量并期望得到一个 Model 数组,但我得到了 BaseModel 改为:

Error message: Cannot assign a value of type [BaseModel] to a value of type [Model]

我是不是漏掉了一些关于泛型的东西?

这是 Playground 的完整代码:

//: Playground - noun: a place where people can play

import UIKit

/// Models:
class BaseModel: NSObject {
var name = ""
}

class Model: BaseModel {
var desc = "abc"
}

/// Services:
class AbstractService<T: NSObject>: NSObject {
var items = [T]()
}

class BaseModelService<T: BaseModel>: AbstractService<BaseModel> {
}

class ModelService<T: Model>: BaseModelService<Model> {
}

/// ViewController:
class ViewController: UIViewController {

let modelService = ModelService()
var items = [Model]()

override func viewDidLoad() {
super.viewDidLoad()

items = modelService.items // The error appears here: Cannot assign a value of type [BaseModel] to a value of type [Model]
}

}

最佳答案

问题是你强制BaseModelService成为 AbstractModelService<BaseModel> 的子类这意味着 items输入 [BaseModel] .声明BaseModelService如下:

class BaseModelService<T: BaseModel>: AbstractService<T> {

那么你就可以开始了。

关于ios - Swift 中的多个泛型类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967079/

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