Swift-错误:初始化前使用变量'self .___' [英] Swift- error: Variable 'self.___' used before being initialized
问题描述
我正在尝试与Playground中的手势识别器配合使用,但遇到了一些麻烦.
I am trying to work with gesture recognizers in a Playground but am having some trouble.
这是我的课程:
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
}
}
我遇到的问题是在以"let gr"开头的行上说初始化之前使用了变量'self.fooVarSwipe'".为什么是这样?我在外面初始化了类,但是它仍然向我显示错误.
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
推荐答案
在内部让gr定位到self,它是foo类的实例. 由于尚未初始化其两个变量,因此当您尝试访问它们时,编译器将引发错误. Swift不接受这种行为.我建议您将它们声明为可选".
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.
这篇关于Swift-错误:初始化前使用变量'self .___'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!