-3

I'm very basic to Swift and trying to convert a text value, multiply its value by 7 and print the output.

WHen I try to print the output I get "lldb"?

Why do I get this error?

@IBAction func findAge(sender: AnyObject) {
    print(age.text!)

    let enteredAge = Int(age.text!)


    let catYears = enteredAge! * 7

    print(String(catYears))


}
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • What error message is shown just above the "lldb" prompt? BTW - that's the debugger prompt since your app just crashed. – rmaddy Apr 04 '17 at 18:07
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – rmaddy Apr 04 '17 at 18:07
  • By the way, you are converting a string to an int. The title is misleading :-) – ElFitz Apr 04 '17 at 18:14
  • @rmaddy:There is no msg shown above the "lldb". – user1050619 Apr 04 '17 at 18:18
  • You should still read through the question and answers I linked. You will learn a lot of very important information. Your code is full of likely crashes due to all the misuses of the `!` operator. – rmaddy Apr 04 '17 at 18:18
  • Try using `print("\(catYears)")` – VitorMM Apr 04 '17 at 18:21
  • just use nil coalescing operator to unwrap and set a default value in case of invalid string is entered `let enteredAge = Int(age.text ?? "") ?? 0` and `let catYears = enteredAge * 7` – Leo Dabus Apr 04 '17 at 18:33
  • Is the "text value", a string taken from a `UITextField`? Or is this an arbitrary `String` text? – KSigWyatt Apr 04 '17 at 19:31
  • 1
    @KSigWyatt "text value" it is the age UITextField text field property which return an optional String so you need to unwrap it also prior to converting it to integer. – Leo Dabus Apr 04 '17 at 20:40

1 Answers1

-2

You should be checking if it can actually be converted to an Integer.

let enteredAge = Int(age.text!)
if enteredAge == nil{
    //do nothing
}
else{
    //multiply by 7
}
Johnd
  • 584
  • 2
  • 6
  • 21