问题
Using swift and Xcode 6, I'm trying to return a value calculated based on content of few UITextFields.
I have declared variables
var Number1 = Field1.text.toInt()
var Number2 = Field2.text.toInt()
var Duration = Number1*Number2
Mylabel.text = String ("\(Duration)")
The idea is to capture duration from few UI Fields and based on calculation of those values assign that to a variable as well as display it on a label.
In line: var Duration = Number1*Number2
Challenge is that I have is that when performing multiplication Xcode highlight error: Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
回答1:
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)"
}
回答2:
Get the value of textFields in var, multiply them, and then set the value of label. Try this:
var Number1 = Field1.text.toInt()
var Number2 = Field2.text.toInt()
var Duration = Number1 * Number2
Mylabel.text = NSString(format:"%d",Duration!)as String;
Hope this helps.. :)
来源:https://stackoverflow.com/questions/25589013/swift-calculate-value-of-uitextfields-and-return-value