Swift:从初始化返回之前,不是在所有路径上都调用了"super.init"吗? [英] Swift: 'super.init' isn't called on all paths before returning from initializer?

查看:153
本文介绍了Swift:从初始化返回之前,不是在所有路径上都调用了"super.init"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一类我的init的最后一个括号中遇到此错误.该类类似于以下内容(我向发生错误的地方推销):

I am getting this error on the last brace of a init in a class of mine. The class looks something like the following (I market the spot where error happens):

class RecordingViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

    let cameraButton:UIButton?
    let camPreview:UIView?

    init (cameraButton: UIButton!, camPreview: UIView!) {
        self.cameraButton = cameraButton
        self.camPreview = camPreview

    } //get error here

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //do a bunch of other stuff
}

我在此处

I have looked here and here for a solution but both seem like solutions that are either really bad or that are too specific to that question, thus they have not work for me.

我希望以一种可以解决我的问题的方式来解决问题,以帮助我理解为什么会发生此错误.

I was hoping for a solution to my problem done in such a way that it can help me understand why this error is happening.

推荐答案

由于您是从UIViewController继承的,因此应在init函数中设置变量后立即调用super.init

Since you inherit from UIViewController, you should call super.init right after you set the variables in your init function

当您继承一个类并实现新的init函数或重写其自己的init函数时,您应该(几乎)始终调用super.init.让我们以您的示例为例,您继承自UIViewController. UIViewController具有一些初始化函数,可用于初始化视图控制器.如果不调用super.init,则这些函数中的所有代码都不会被调用,并且可能不会初始化视图控制器.

When you inherit a class and implement a new init function or override its own init function you should (almost) always call super.init. Let's take your example, you inherited from UIViewController. UIViewController has a few init functions that you can use to initialize a view controller. if you don't call super.init, all the code inside those functions will not get called and possibly the view controller won't get initialized.

无论如何,这段代码应该对您有用:

Anyway, this piece of code should work for you:

class ViewController: UIViewController {

    var button: UIButton?

    init(button: UIButton) {
        self.button = button
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

这篇关于Swift:从初始化返回之前,不是在所有路径上都调用了"super.init"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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