Swift- error: Variable 'self.___' used before being initialized

亡梦爱人 提交于 2019-12-19 21:21:08

问题


I am trying to work with gesture recognizers in a Playground but am having some trouble.

Here is my class:

class foo {

    var fooVarSwipe: Any
    var fooVarTap: Any

    init() {

        let gr = UISwipeGestureRecognizer(target: self, action: #selector(foo.bar))
        let tr = UITapGestureRecognizer(target: self, action: #selector(foo.tar))
        helloApple.addGestureRecognizer(gr)
        helloApple.addGestureRecognizer(tr)
        helloApple.isUserInteractionEnabled = true
        self.fooVarSwipe = gr
        self.fooVarTap = tr

    }



    @objc func tar() {
        print("tapped")
    }

    @objc func bar() {
        print("swiped")
        currentViewNum = 1
    }
}

The problem I am having is that on the line starting with "let gr" it is saying "Variable 'self.fooVarSwipe' used before being initialized." Why is this? I initialize the class outside but it still is showing me the error.

Any help would be much appreciated!! Cheers and thanks in advance, Theo


回答1:


Inside let gr you are targeting self, which is an instance of class foo. Since you haven't initialised its two variables, compiler throws an error when you try to access them. Swift doesn't accept this behaviour. I suggest you to declare them as Optional.



来源:https://stackoverflow.com/questions/42729347/swift-error-variable-self-used-before-being-initialized

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