Swift 'open' keyword & overridable method/properties in extension?

ε祈祈猫儿з 提交于 2019-12-03 06:14:51

Unless I am mistaken, you can declare the extension methods as open in your framework if you just omit the public keyword in the extension declaration:

extension UIManagedDocument {

    open class func primaryDocumentName() -> String {
        return "Document"
    }
    // ...
}

And then (for NSObject subclasses or @objc members) you can override the method in your custom subclass in the main application (or in any module):

class MyManagedDocument: UIManagedDocument {

    override class func primaryDocumentName() -> String {
        return "MyDocument"
    }
    // ...
}
  • 'Protocol-oriented' - declare protocol with desired methods/properties then refactor your extension for protocol compliance.
  • 'Traditional' - implement intermediate (abstract) subclass with desired methods/properties.

Protocol example:

protocol PrimaryDocument {
    static func primaryDocumentName() -> String

    static func primaryStoreURL() -> URL

    static func primaryModelName() -> String?
}

extension UIManagedDocument : PrimaryDocument {

    open class func primaryDocumentName() -> String {
        return "Document"
    }

    open class func primaryStoreURL() -> URL {
        let documentsURL = FileManager.default.userDocumentsURL
        return URL(fileURLWithPath: self.primaryDocumentName(), isDirectory: false, relativeTo: documentsURL)
    }

    open class func primaryModelName() -> String? {
        return "Model"
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!