以下类具有let声明为隐式展开变量的' '属性.以前这适用于Xcode 6.2:
class SubView: UIView {
let pandGestureRecognizer: UIPanGestureRecognizer!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.pandGestureRecognizer = UIPanGestureRecognizer(target: self, action: "panAction:")
}
func panAction(gesture: UIPanGestureRecognizer) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
更新到Xcode 6.3(使用Swift 1.2)后,会发生以下编译错误:
Property 'self.panGestureRecognizer' not initialized at super.init call
Immutable value 'self.panGestureRecognizer' may only be initialized once
Run Code Online (Sandbox Code Playgroud)
在super.init通话前移动以下行:
self.pandGestureRecognizer = UIPanGestureRecognizer(target: self, action: "panAction:")
Run Code Online (Sandbox Code Playgroud)
给出以下错误:
'self' is used before super.init call
Run Code Online (Sandbox Code Playgroud)
该属性' panGestureRecognizer'不需要变异,因此必须将其声明为常量' let'.由于它是常量,因此必须在声明时具有初始值,或者在init方法中初始化它.要初始化它,需要self在' target'参数中传递' ' .
其他线程建议将其声明为隐式解包可选,并在super.init调用后初始化它.这之前一直有效,直到我更新到Xcode 6.3.
有没有人知道这种情况的正确实施或解决方法?
ABa*_*ith 12
问题
问题是你使用let- 声明的选项let没有给出默认值nil(var但是).以下是在Swift 1.2中引入的,否则将无效,因为myOptional在声明之后您将无法给出值:
let myOptional: Int?
if myCondition {
myOptional = 1
} else {
myOptional = nil
}
Run Code Online (Sandbox Code Playgroud)
因此,你得到错误'属性'self.panGestureRecognizer'没有在super.init调用'初始化'因为在调用之前super.init(coder: aDecoder),因为panGestureRecognizer不是nil; 它根本没有初始化.
解决方案:
1.声明panGestureRecognizer为a var,意味着它将被赋予默认值nil,然后您可以在调用后更改super.init(coder: aDecoder).
2.在我看来,更好的解决方案是:不要使用隐式解包的可选项,并panGestureRecognizer使用初始值声明UIPanGestureRecognizer().然后在super.init调用之后设置目标:
class SubView: UIView {
let panGestureRecognizer = UIPanGestureRecognizer()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
panGestureRecognizer.addTarget(self, action: Selector("panAction:"))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5750 次 |
| 最近记录: |