In earlier swift versions (3x), We can override initialize() method of a class which gives you a compile time warning like shown below.
In latest Xcode 9 and above, We can set the Swift the version.
It is clearly saying that, The support will be disallowed in future.
So, From Swift 4, We are not suppose to override Objective-C class method initialize(), Which gives build error like shown below.
Method ‘initialize()’ defines Objective-C class method ‘initialize’, which is not permitted by Swift.
Swift 3 versions warning became error in Swift 4.
In this post let’s see the alternate approach to get rid of this build error.
Like In my earlier Method Swizzling posts, If need something needs to be executed like Method swizzling in Swift, We can write that in method and call that in AppDelegate didFinishLaunchWithOptions
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
static func swizzleViewWillAppear() {
if self != UIViewController.self {
return
}
let _: () = {
let originalSelector = #selector(UIViewController.viewWillAppear(_:))
let swizzledSelector = #selector(UIViewController.newViewWillAppear(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod!, swizzledMethod!);
}()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIViewController.swizzleViewWillAppear()
return true
}
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
The only extra step is we need to call that method explicitly to get it applied, Whereas using initialize() like in earlier versions, we don’t need to as initialize() will get called automatically.
Hope this post is useful. Feel free to comment incase of any queries.
Nice Blog.
ReplyDeleteI had a look at your blog in detail and seems that it is very useful for all the users who are looking to understand the Method ‘initailize()’ which defines Objective-C class method ‘initialize’, which is not guaranteed to be invoked by Swift and will be disallowed in future versions. I was looking for swift application development company
Its good and Informative.Thank you for posting this article.
ReplyDeleteios app development course