Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uikit

swift

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

like image 923
Theo Strauss Avatar asked Mar 10 '17 23:03

Theo Strauss


1 Answers

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.

like image 105
mattd Avatar answered Nov 12 '22 01:11

mattd