Swift初始化悖论 [英] Swift initialization paradox
问题描述
在UIView
的子类中,我声明了一个属性.此属性是UIPanGestureRecognizer
的实例,不是可选的或隐式解包的.这是代码:
In a subclass of UIView
I declared a property. This property is an instance of UIPanGestureRecognizer
and is not optional or implicitly unwrapped. Here is the code:
class DraggableView: UIView {
let panGestureRecognizer: UIPanGestureRecognizer
override init() {
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "dragged:")
super.init()
backgroundColor = UIColor.greenColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在panGestureRecognizer
Xcode的初始化行上,出现错误:"super.init调用前已使用自我".如果将super.init()
行移到panGestureRecognizer
初始化行的上方,则Xcode会出现另一个错误:属性self.panGestureRecognizer
在调用super.init
时未初始化".最后一次尝试是在init
方法之外的声明中初始化panGestureRecognizer
.像这样:
Here on the the initialization line of panGestureRecognizer
Xcode gives an error: "self used before super.init call". If I move super.init()
line above the panGestureRecognizer
initialization line, Xcode gives another error: "Property self.panGestureRecognizer
not initialized at super.init
call". The last attempt made was to initialize panGestureRecognizer
in its declaration outside of the init
method. Like this:
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "dragged:")
此处Xcode给出了另一个错误:类型DraggableView -> () -> DraggableView!
不符合协议AnyObject
"
Here Xcode gives yet another error: "Type DraggableView -> () -> DraggableView!
does not conform to protocol AnyObject
"
有没有一种方法可以在不使用可选选项或隐式展开的可选选项的情况下完成这项工作?
Is there a way to make this work without using optionals or implicitly unwrapped optionals?
推荐答案
问题是self
在super.init()
发生之前不存在.
The problem is that self
doesn't exist before super.init()
has happened.
您可以分两步创建它-在声明时进行初始化:
You can create it in two steps - initialise at declaration time:
let panGestureRecognizer = UIPanGestureRecognizer()
然后在super.init()
之后,添加目标:
Then after super.init()
, add the target:
panGestureRecognizer.addTarget(self, action: "dragged:")
或者,您也可以将其设置为lazy var
,但我不喜欢使事物可变,除非它们应该变化.
Alternatively you could make it a lazy var
but I don't like making things variable unless they're supposed to vary.
这篇关于Swift初始化悖论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!