Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to override private method and call super in swift?

Tags:

swift

as we know, if you need to override a method in base class in swift, you have to declare "override" keyword before that method. if that method is private, you can still "override" it in swift, just add NO override keyword. However, you can not call super.MethodName(), that's my problem.

say, there's a private method in UINavigationController, namely "_startCustomTransition", I can do this in my custom MyNavigationController.swift

class MyNavigationController: UINavigationController {
    func _startCustomTransition() {
        // I can not call super._startCustomTransition()
    }
}

So, how can I do that super call? Thanks.

like image 766
george Avatar asked Jul 21 '17 03:07

george


1 Answers

You must deceive the Swift compiler that such method exists. For that you can simply add an Object-C extension declaration to the bridging header of your project:

@import UIKit;

@interface UINavigationController(PrivateMethods)

- (void)_startCustomTransition;

@end

Now, you can override the method without problems:

class MyNavigationController: UINavigationController {
    override func _startCustomTransition() {
        super._startCustomTransition()
    }
}

EDIT: You have to declare the method in an Objective-C extension, because I see no way to declare a method in a Swift extension without implementing it. Suggestions are very welcome. :)

like image 82
clemens Avatar answered Sep 24 '22 21:09

clemens