Swift - How to override an init function? (Was a category in Objective-C)

半城伤御伤魂 提交于 2019-12-13 05:16:25

问题


I have an Objective-C category used to customise

UIStoryboard's '+ (UIStoryboard *)storyboardWithName:(NSString *)name'.

It is used to determine which storyboard file to call when dealing with multiple devices. Now I need to change it to Swift.

It seems that I need to create a "Swift Extension", but am having issues getting it to work.

Here is what I have:

extension UIStoryboard {
    convenience init(name: String, storyboardBundleOrNil: NSBundle?)
    {
        var storyboard: UIStoryboard?
        var storyboardName: String?

        // Don't adjust name if it's universal storyboard (Xcode 6, iOS 8)
        storyboardName = name;

        if (name.rangeOfString("_Universal") == nil)
        {
            if (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
            {
                storyboardName = storyboardName!+"_iPad"
            }
            else
            {
                storyboardName = storyboardName!+"_iPhone"
            }
        }
//        storyboard = UIStoryboard(name: storyboardName!, storyboardBundleOrNil: storyboardBundleOrNil!)
        assert(storyboard != nil, "Storyboard %@ not found!")
        //return storyboard!;
        self.init(name: storyboardName!, storyboardBundleOrNil: storyboardBundleOrNil!)
    }
}

回答1:


You cannot override a Swift method in an extension. See the documentation on Extensions for reference.

You cannot use extensions to override existing methods or properties on Objective-C types.

You've also used the wrong signature. The correct signature is

init(name: String, bundle: NSBundle?)

It will allow you to create the convenience initializer, and it will use it when you call it in your own code, but the framework's implementation gets called from external code. It seems like a bug to me that it will allow you to declare an extension convenience initializer with the same name, as I can't find a way to call the original initializer, so you will just get infinite recursion the way you've written it.



来源:https://stackoverflow.com/questions/26664213/swift-how-to-override-an-init-function-was-a-category-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!