ios - 我可以覆盖在 Swift 中使用协议(protocol)声明的通用属性吗?

标签 ios swift cocoa-touch inheritance overriding

这样的方法在 Swift 中会很好还是一个坏主意:

protocol Serializable {
    func serealize()
}

class SomeBaseVC: UIViewController {

    var serialisableObject: Serializable?


    override func viewDidLoad() {
        super.viewDidLoad()
        serialisableObject?.serealize()
        //Do some other generic stuff with serialisableObject
    }

}

class JSONObject: Serializable {
    func serealize() {
        //serealize
    }


}

class SomeChildVCWhichHasSomeGenericBehaviour: SomeBaseVC {
    override var serialisableObject: JSONObject

    override func viewDidLoad() {
        super.viewDidLoad() //Now this would do serealisation of JSONObject
        //And now do something specific to just this VC
    }
}

所以重点是让我的许多 View Controller 共享一些通用行为,这些行为在我的父类(super class)中使用协议(protocol)实现。假设我有很多 View Controller 需要序列化一些对象并将其保存在 viewDidLoad 方法中(这显然是一个假设的例子)。这可能是一些 JSON 数据或一些 XML 数据。现在我可以每次都实现不同的 viewDidLoad 方法,具体取决于 Controller 是使用 XML 还是 JSON,但如上所示,我认为我可以将它封装在基类中,然后我可以从这个基类 VC 继承并调用 super。 viewDidLoad()。唯一困扰我的部分是:

override var serialisableObject: JSONObject

我可以这样做吗?这是个好主意吗?

最佳答案

您不能更改 serialisableObject 的类型,因为那样会违反 LSP

您可以使用 setter/getter 有效地将子类中的另一个属性别名为父类(super class) serialisableObject 属性。这将允许您在 View Controller 子类中使用特定类型,而父类(super class)将使用别名:

class SomeChildVCWhichHasSomeGenericBehaviour: SomeBaseVC {

    var jsonThing: JSONObject?

    override var serialisableObject: Serializable? {
        get {
            return jsonThing
        }

        set {
            self.jsonThing = newValue as? JSONObject
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad() //Now this would do de-serealisation of JSONObject
        print(self.jsonThing) 
    }
}

关于ios - 我可以覆盖在 Swift 中使用协议(protocol)声明的通用属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40209385/

相关文章:

ios - 下拉表格 View 单元格

iphone - 如何在 Xcode 中将数据传递到另一个 Storyboard?

ios - UICollectionViewCell : Are there any events fired when cell visibility changes?

ios - 选中和取消选中 TableView Controller 中的按钮

ios - 为什么第二次在 iOS 上执行事件会更快?

iphone - 如何将 UILabel 放在 UIToolbar 之上?

android - 如何在 react-native 中添加破折号或虚线边框?

ios - 移动和动画 UIView

javascript - 专注于模式内的输入会导致 ios 向下滚动

ios - 将图像置于按钮中会产生意想不到的结果