The toInt() method returns an optional value because the string it is trying to convert may not contain a proper value. For instance, these strings will be converted to nil: "house", "3.7","" (empty string).
Because the values may be nil, toInt() returns an optional Int which is the type Int?. You can't use that value without unwrapping it first. That is why you are getting the error message. Here are two safe ways to handle this:
You need to decide what you want to do when a value can't be converted. If you just want to use 0 in that case, then use the nil coalescing operator (??) like so:
let number1 = field1.text.toInt() ?? 0
// number1 now has the unwrapped Int from field1 or 0 if it couldn't be converted
let number2 = field2.text.toInt() ?? 0
// number2 now has the unwrapped Int from field2 or 0 if it couldn't be converted
let duration = number1 * number2
mylabel.text = "\(duration)"
If you want your program to do nothing unless both fields have valid values:
if let number1 = field1.text.toInt() {
// if we get here, number1 contains the valid unwrapped Int from field1
if let number2 = field2.text.toInt() {
// if we get here, number2 contains the valid unwrapped Int from field2
let duration = number1 * number2
mylabel.text = "\(duration)"
}
}
So, what did the error message mean when it said did you mean to use a !. You can unwrap an optional value by adding a ! to the end, but you must be absolutely sure the value is not nil first or your app will crash. So you could also do it this way:
if number1 != nil && number2 != nil {
let duration = number1! * number2!
mylabel.text = "\(duration)"
}