“initialize” class method for classes in Swift?

后端 未结 6 1089
日久生厌
日久生厌 2020-12-04 11:55

I\'m looking for behavior similar to Objective-C\'s +(void)initialize class method, in that the method is called once when the class is initialized, and never a

6条回答
  •  日久生厌
    2020-12-04 12:33

    @aleclarson nailed it, but as of recent Swift 4 you cannot directly override initialize. You still can achieve it with Objective-C and categories for classes inheriting from NSObject with a class / static swiftyInitialize method, which gets invoked from Objective-C in MyClass.m, which you include in compile sources alongside MyClass.swift:

    # MyView.swift
    
    import Foundation
    public class MyView: UIView
    {
        @objc public static func swiftyInitialize() {
            Swift.print("Rock 'n' roll!")
        }
    }
    
    # MyView.m
    
    #import "MyProject-Swift.h"
    @implementation MyView (private)
        + (void)initialize { [self swiftyInitialize]; }
    @end
    

    If your class cannot inherit from NSObject and using +load instead of +initialize is a suitable fit, you can do something like this:

    # MyClass.swift
    
    import Foundation
    public class MyClass
    {
        public static func load() {
            Swift.print("Rock 'n' roll!")
        }
    }
    public class MyClassObjC: NSObject
    {
        @objc public static func swiftyLoad() {
            MyClass.load()
        }
    }
    
    # MyClass.m
    
    #import "MyProject-Swift.h"
    @implementation MyClassObjC (private)
        + (void)load { [self swiftyLoad]; }
    @end
    

    There are couple of gotchas, especially when using this approach in static libraries, check out the complete post on Medium for details! ✌️

提交回复
热议问题