考慮我有一個模型,併爲它的基本模型:多泛型類繼承
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
!而非:
我是否錯過了泛型?
下面是遊樂場的全碼:
//: 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]
}
}
非常感謝你,現在工作得很好! –