swift - Fatal error , can't unwrap optional none -
this simple problem , can't solve , have following full code
var numberoftimer:int = 0 func increment(){ numberoftimer = numberoftimer + 1 //error here,breakpoint,no error message if numberoftimer>4{ falafel1.center = cgpointmake(200, 100) } } @iboutlet var fryer:uiimageview @iboutlet var order : uilabel var numberofflafel:uint32! init(nibname nibnameornil: string?, bundle nibbundleornil: nsbundle?) { super.init(nibname: nibnameornil, bundle: nibbundleornil) // custom initialization } override func viewdidload() { super.viewdidload() numberofflafel = arc4random()%11 if numberofflafel<2{ order.text = "make \(numberofflafel) falafel" } order.text = "make \(numberofflafel) falafels" } init(coder adecoder: nscoder!) { super.init(coder: adecoder) } override func touchesmoved(touches: nsset!, withevent event: uievent!) { let t = touches.anyobject() uitouch if t.view == falafel1{ let p = t.locationinview(self.view) falafel1.center = p if cgrectintersectsrect(falafel1.frame, fryer.frame){ falafel1.center = cgpointmake(385, 192) nstimer.scheduledtimerwithtimeinterval(1 , target: self, selector: "increment", userinfo: nil, repeats: true) } }
this gives me run time error saying can't unwrap optional none , because i'm accessing doesn't have value , in case , how can solve problem
var num: int?
declares optional variable, automatically initialized nil
(aka optional none), indicating "missing" value. therefore
num = num! + 1
crashes @ runtime, because no value has been assigned variable.
using optional seems not necessary in case, should declare as
var num: int = 0 // integer variable initial value 0
and remove "unwrapping" operator !
in method:
func function() { num = num + 1 // or simply: ++num if num > 5 { // ... } }
Comments
Post a Comment