Swift - Objective-C load class method?

前端 未结 7 1864
暗喜
暗喜 2020-12-01 18:28

In Objective-C, NSObject had a class method called load that gets called when the class is loaded for the first time. What is the equivalent in Swi

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 18:59

    What is the equivalent in Swift?

    There is none.

    Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

    Source: "The Swift Programming Language", by Apple

    Types simply don't have an initializer in Swift. As several answers here suggest, you may be able to work around that by using the Objective-C bridge and having your Swift class inherit from NSObject or by using a Objective-C loader bootstrap code but if you have a 100% Swift project, you basically only have two options:

    1. Manually initialize your classes somewhere within the code:
    class MyCoolClass {
    
        static func initClass ( ) {
            // Do your init stuff here...
        }
    }
    
    
    // Somewhere in a method/function that is guaranteed to be called
    // on app startup or at some other relevant event:
    MyCoolClass.initClass()
    
    1. Use a run once pattern in all methods that require an initialized class:
    class MyCoolClass {
    
        private static var classInitialized: Bool = {
             // Do your init stuff here...
             // This code will for sure only run once!
             return true
        }()
    
        private static func ensureClassIsInitialized ( ) { 
            _ = self.classInitialized 
        }
    
    
        func whateverA ( ... ) {
            MyCoolClass.ensureClassIsInitialized()
            // Do something...
        }
    
        func whateverB ( ... ) {
            MyCoolClass.ensureClassIsInitialized()
            // Do something...
        }
    
    
        func whateverC ( ... ) {
            MyCoolClass.ensureClassIsInitialized()
            // Do something...
        }
    
    }
    

    This follows a clean pattern that no code in Swift runs "automagically", code only runs if other code instructs it to run, which provides a clear and trackable code flow.

    There might be a better solution for special cases yet you have not provided any information as for why you need that feature to begin with.

提交回复
热议问题