斯威夫特——错误:变量的自我。___在初始化之前使用

时间:2022-11-05 17:10:02

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.

我遇到的问题是,在一行中以"let gr"开头的是"Variable " self。在初始化之前使用的fooVarSwipe。这是为什么呢?我在外面初始化了类,但是它仍然显示了错误。

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

如有任何帮助,我们将不胜感激!提前谢谢你,西奥。

1 个解决方案

#1


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.

在内部让gr您瞄准self,这是一个类foo的实例。由于您还没有初始化它的两个变量,所以当您试图访问它们时,编译器会抛出一个错误。斯威夫特不接受这种行为。我建议你声明它们是可选的。

#1


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.

在内部让gr您瞄准self,这是一个类foo的实例。由于您还没有初始化它的两个变量,所以当您试图访问它们时,编译器会抛出一个错误。斯威夫特不接受这种行为。我建议你声明它们是可选的。