我正在尝试以通用方式实现项目的特定部分,但是我正在努力进行类型检查。模型有两种类型-Service
和Product
(1-N关系)。在下面的代码中,Service
被视为节,而Product
被视为节项目。
protocol ItemSectionable: class {
associatedtype SectionItemType
func getSection() -> Int
func getSectionName() -> String
func getItem(index: Int) -> SectionItemType
}
class Service: Object, Model, ItemSectionable {
typealias ModelType = Service
typealias SectionItemType = Product
@objc dynamic var id: Int = 0
@objc dynamic var name: String = ""
@objc dynamic var enabled: Bool = false
@objc dynamic var deleted: Bool = false
@objc dynamic var createdAt = Date()
@objc dynamic var updatedAt = Date()
let products = List<Product>()
override static func primaryKey() -> String? {
return "id"
}
static func newInstance(values: Object) -> Service {
let _service = values as! Service
let service = Service(value: _service)
_service.products.forEach { _product in
service.products.append(Product(value: _product))
}
return service
}
func getSection() -> Int {
return products.count
}
func getSectionName() -> String {
return name
}
func getItem(index: Int) -> Product {
return products[index]
}
}
class Product: Object, Model {
typealias ModelType = Product
@objc dynamic var id: Int = 0
@objc dynamic var name: String = ""
@objc dynamic var code: String = ""
@objc dynamic var salesPrice: Float = 0
@objc dynamic var deleted: Bool = false
@objc dynamic var createdAt = Date()
@objc dynamic var updatedAt = Date()
let service = LinkingObjects(fromType: Service.self, property: "products")
override static func primaryKey() -> String? {
return "id"
}
static func newInstance(values: Object) -> Product {
let product = Product(value: values)
return product
}
}
此外,我有一个通用的RealmListSectionModelManager
,它扩展了RealmListModelManager
的大部分功能,并实现了将数据拆分为多个部分的支持。
class RealmListSectionModelManager<T: Model & ItemSectionable>: RealmListModelManager<T> where T: Object {
// Get number of sections
override func getSectionCount() -> Int {
return data?.count ?? 1
}
// Get number of items in a section
override func getSectionItemCount(section: Int = 0) -> Int {
return data?[section].getSection() ?? 0
}
// Get item for a specific section
override func getItem(index: Int, section: Int) -> ItemSectionable.SectionItemType <-- No idea how to write this correctly {
return data![section].getItem(index: index)
}
}
我遇到的问题是关于getItem(index: Int, section: Int)
中的RealmListSectionModelManager
函数,该函数应返回基于ItemSectionable's associatedtype
(SectionItemType
)的类型,但是我不知道如何正确地做到这一点。