Swift 计算 UITextFields 的值并返回值 [英] Swift calculate value of UITextFields and return value
问题描述
使用 swift 和 Xcode 6,我试图返回一个基于几个 UITextField 的内容计算的值.
Using swift and Xcode 6, I'm trying to return a value calculated based on content of few UITextFields.
我已经声明了变量
var Number1 = Field1.text.toInt()
var Number2 = Field2.text.toInt()
var Duration = Number1*Number2
Mylabel.text = String ("\(Duration)")
这个想法是从几个 UI 字段中捕获持续时间,并根据这些值的计算将其分配给变量并将其显示在标签上.
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.
在线:var Duration = Number1*Number2
In line: var Duration = Number1*Number2
我遇到的挑战是在执行乘法时 Xcode 高亮错误:可选类型Int?"的值未解开;你的意思是使用!"还是?"?
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 '?'?
推荐答案
toInt()
方法返回一个 optional 值,因为它尝试转换的字符串可能不包含适当的值.例如,这些字符串将被转换为 nil
: "house"
, "3.7"
,""
(空字符串).
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).
因为值可能是 nil
,toInt()
返回一个可选的 Int
,它的类型是 Int?
>.如果不先打开它,就不能使用该值.这就是您收到错误消息的原因.以下是两种安全的处理方法:
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:
当值无法转换时,您需要决定要做什么.如果你只是想在这种情况下使用 0
,那么使用 nil 合并运算符 (??
) 像这样:
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)"
}
}
那么,当错误消息说您要使用 !
时,它是什么意思.您可以通过在末尾添加 !
来解开一个可选值,但是首先您必须绝对确定该值不是 nil,否则您的应用会崩溃.所以你也可以这样做:
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)"
}
这篇关于Swift 计算 UITextFields 的值并返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!