Swift-如何覆盖一个初始化函数? (是Objective-C中的类别) [英] Swift - How to override an init function? (Was a category in Objective-C)

查看:156
本文介绍了Swift-如何覆盖一个初始化函数? (是Objective-C中的类别)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于自定义的 Objective-C 类别

I have an Objective-C category used to customise

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

它用于确定在处理多个设备时要调用哪个情节提要文件.现在我需要将其更改为Swift.

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.

这就是我所拥有的:

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!)
    }
}

推荐答案

您不能在扩展中覆盖Swift方法.

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

您不能使用扩展来覆盖Objective-C类型上的现有方法或属性.

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.

这篇关于Swift-如何覆盖一个初始化函数? (是Objective-C中的类别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆