swift - unexpectedly found nil while unwrapping an Optional value, when trying to cover toInt() -
i new in swift , trying build simple program converts number of week in days, minutes , seconds, cannot convert string
int
. when thought done using toint()
, message appeared in line:
var tempoemdias:int! = timeindays.text.toint()
,
fatal error: unexpectedly found nil while unwrapping optional value...
does can me? code below...
import uikit class viewcontroller: uiviewcontroller { @iboutlet var timeindays: uitextfield! @iboutlet var numberofweeks: uilabel! @iboutlet var numberofhours: uilabel! @iboutlet var numberofminutes: uilabel! @iboutlet var numberofseconds: uilabel! @ibaction func calculatempo(sender: anyobject) { // below: fatal error: unexpectedly found nil while unwrapping optional value. var tempoemdias:int! = timeindays.text.toint() // calcula semana var numerodesemanas:int = 0 if tempoemdias! <= 7 { numerodesemanas = 1 } else { numerodesemanas = tempoemdias! / 7 } let numerodesemanascerto:int = int(numerodesemanas) numberofweeks.text = "/(numerodesemanascerto) semanas" // calcula horas let numerodehoras = numerodesemanascerto * 24 numberofhours.text = "/(numerodehoras) horas" // calcula minutos let numerodeminutos = numerodehoras * 60 numberofminutes.text = "/(numerodeminutos) minutos" // calcula segundos let numerodesegundos = numerodeminutos * 60 numberofseconds.text = "/(numerodesegundos) segundos" }
you error because toint() returns optional integer value , trying assign non-optional tempoemdias
.
from documentation:
toint() use method convert string integer value. method returns optional integer value (int?)—if conversion succeeds, value resulting integer; if conversion fails, value nil: let string = "42" if let number = string.toint() { println("got number: \(number)") } else { println("couldn't convert number") } // prints "got number: 42"
Comments
Post a Comment