ios - Pass self as argument within init method in Swift 1.2 -
the following class has 'let
' property declared implicitly unwrapped variable. worked 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) { // ... } }
after updating xcode 6.3 (with swift 1.2), following compilation errors occur:
property 'self.pangesturerecognizer' not initialized @ super.init call immutable value 'self.pangesturerecognizer' may initialized once
moving following line before super.init
call:
self.pandgesturerecognizer = uipangesturerecognizer(target: self, action: "panaction:")
gives following error:
'self' used before super.init call
the property 'pangesturerecognizer
' requires no mutation, therefore has declared constant 'let
'. since constant, has have initial value upon declaration, or initialize within init
method. initialize it, requires pass 'self
' in 'target
' parameter.
other thread suggested declare implicitly unwrapped optional, , initialize after super.init
call. worked until updated xcode 6.3.
does know proper implementation or workaround case?
the problem
the problem use of let
- optionals declared let
aren't given default value of nil
(var
however). following, introduced in swift 1.2, wouldn't valid otherwise since wouldn't able give myoptional
value after declaring it:
let myoptional: int? if mycondition { myoptional = 1 } else { myoptional = nil }
therefore, you're getting error 'property 'self.pangesturerecognizer' not initialized @ super.init call' because before calling super.init(coder: adecoder)
, because pangesturerecognizer
isn't nil
; hasn't been initialised @ all.
the solutions:
1. declare pangesturerecognizer
var
, meaning given default value of nil
, change after calling super.init(coder: adecoder)
.
2. in opinion, better solution: don't use implicitly unwrapped optional , declare pangesturerecognizer
initial value of uipangesturerecognizer()
. set target after super.init
called:
class subview: uiview { let pangesturerecognizer = uipangesturerecognizer() required init(coder adecoder: nscoder) { super.init(coder: adecoder) pangesturerecognizer.addtarget(self, action: selector("panaction:")) } }
Comments
Post a Comment