无法将变量设置为文本字段的值
Can't set a variable to the value of a textfield
我正在尝试获取 UITextField
的文本值,将其转换为 Double
,并将其保存到变量中。但是,我收到错误消息:
Expression type '@lvalue String?' is ambiguous without more context.
这是什么意思?
class SituationViewController: GBBaseViewController {
// ....
@IBOutlet var txtConsumption: UITextField!
func fillValues(){
let consumption = Double(self.txtConsumption.text) ?? 0 // the error happens here
}
}
问题是 UITextField
的 text
属性 是 Optional
,但 Double
的初始化程序需要 non-Optional String
。只需为字符串提供一个默认值。
let consumption = Double(self.txtConsumption.text ?? "") ?? 0
试试这个:
func fillValues() {
if let myText = self.txtConsumption.text { // Check if txtConsumption has a value
let consumption = Double(myText) ?? 0
}
}
错误发生是因为 txtConsumption.text 可以为 nil,Double 需要一个 no-nil 参数作为初始值设定项。
我正在尝试获取 UITextField
的文本值,将其转换为 Double
,并将其保存到变量中。但是,我收到错误消息:
Expression type '@lvalue String?' is ambiguous without more context.
这是什么意思?
class SituationViewController: GBBaseViewController {
// ....
@IBOutlet var txtConsumption: UITextField!
func fillValues(){
let consumption = Double(self.txtConsumption.text) ?? 0 // the error happens here
}
}
问题是 UITextField
的 text
属性 是 Optional
,但 Double
的初始化程序需要 non-Optional String
。只需为字符串提供一个默认值。
let consumption = Double(self.txtConsumption.text ?? "") ?? 0
试试这个:
func fillValues() {
if let myText = self.txtConsumption.text { // Check if txtConsumption has a value
let consumption = Double(myText) ?? 0
}
}
错误发生是因为 txtConsumption.text 可以为 nil,Double 需要一个 no-nil 参数作为初始值设定项。