修改子类中继承自父类的属性的类型

在使用 UITableView 时,经常创建具体的模型来简化代码:

class Section: NSObject {

    var items: [Item]
    
    init(items: [Item]) {
        self.items = items
    }
}

class Item: NSObject {

    var title: String
    
    init(title: String) {
        self.title = title
    }
}

// ----------

var sections = [Section]()

let item = Item(title: "Title")
let section = Section(items: [item])
sections.append(section)

然后在 UITableView 的数据源方法中实现:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
    let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.self, for: indexPath)
        
    let item = sections[indexPath.section].items[indexPath.row] 
        
    cell.item = item
        
    return cell
}

但是当存在多种类型的 Cell 时,需要创建具体的模型来继承基础模型:

class SectionA: Section {
    var some: String?
}

class ItemA: Item {
    var isEdit = false
}

此时会产成一个问题,当在 UITableView 的数据源方法中实现模型传递时,需要强转类型:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
    let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.self, for: indexPath)
        
    let item = sections[indexPath.section].items[indexPath.row] as! SectionA
        
    cell.item = item
        
    return cell
}

如何直接获取类型,而不需要强转呢?需要使用泛型:

class Section<T: Item>: NSObject {

    var items: [T]
    
    init(items: [T]) {
        self.items = items
    }
}

class Item: NSObject {

    var title: String
    
    init(title: String) {
        self.title = title
    }
}

// ----------

class SectionA: Section<ItemA> {
    var some: String?
}

class ItemA: Item {
    var isEdit = false
}

// ----------
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容