美文网首页
修改子类中继承自父类的属性的类型

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

作者: 冰霜海胆 | 来源:发表于2018-09-09 13:16 被阅读6次

在使用 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
}

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

相关文章

  • Python面向对象编程-3·继承

    一、继承的概念: 子类 拥有 父类 的所有 方法 和 属性 子类 继承自 父类,可以直接 享受 父类中已经封装好的...

  • Swift之属性重写

    引入 属性继承:子类可以继承父类的属性,包括存储属性、计算属性和类型属性,还可以继承父类的属性观察器。属性重写需要...

  • 389,swift中属性的重载(计算属性和存储属性的重载:关键字

    引入 属性继承:子类可以继承父类的属性,包括存储属性、计算属性和类型属性,还可以继承父类的属性观察器。属性重写需要...

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

    在使用 UITableView 时,经常创建具体的模型来简化代码: 然后在 UITableView 的数据源方法中...

  • Java_basic_8: 继承

    继承 继承的特点 子类,父类 单继承(一个子类只有一个父类) 父类中private 的属性不能被继承 继承的好处 ...

  • Swift 5.1 (13) - 继承

    继承 继承是一种基本行为:子类继承父类方法,属性和其他特性。子类可以重写父类的方法,属性。继承将类与Swift中的...

  • 通过反射给没有 setter 方法的属性赋值,包括父类属性

    需求 在 Junit 中,有时需要为子类继承自父类的属性赋值,但是父类中的属性没有提供 setter 方法,此时可...

  • Dart学习笔记——面向对象(二)

    继承 简单继承 Dart中的类的继承: 子类使用extends关键词来继承父类。 子类会继承父类里面可见的属性和方...

  • Python 继承

    1、单继承 子类在继承的时候,在定义类时,小括号()中为父类的名字,父类的属性、方法,会被继承给子类。虽然子类没有...

  • PHP 继承、封装、多态

    一、继承 -子类只能继承父类的非私有属性-子类继承父类后,相当于将父类的属性和方法copy到子类,可以直接使用$t...

网友评论

      本文标题:修改子类中继承自父类的属性的类型

      本文链接:https://www.haomeiwen.com/subject/nhorgftx.html