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

后端 未结 2 594
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 05:57

With introduction of open keyword in Swift 3.0 (What is the \'open\' keyword in Swift?).

Note: Limited to extensions on NSObject derived classes

相关标签:
2条回答
  • 2021-02-08 06:26
    • '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"
        }
    
    }
    
    0 讨论(0)
  • 2021-02-08 06:35

    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"
        }
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题