Reputation: 8177
I'm trying to get the text value of a UITextField
, convert it to a Double
, and save it to a variable. However, I'm getting the error:
Expression type '@lvalue String?' is ambiguous without more context.
What does that mean?
class SituationViewController: GBBaseViewController {
// ....
@IBOutlet var txtConsumption: UITextField!
func fillValues(){
let consumption = Double(self.txtConsumption.text) ?? 0 // the error happens here
}
}
Upvotes: 0
Views: 133
Reputation: 363
Try this:
func fillValues() {
if let myText = self.txtConsumption.text { // Check if txtConsumption has a value
let consumption = Double(myText) ?? 0
}
}
The error happened because txtConsumption.text can be nil, Double need a no-nil parameter for initializer.
Upvotes: 0
Reputation: 54716
The issue is that the text
property of UITextField
is an Optional
, but the initialiser of Double
needs a non-Optional String
. Just provide a default value for the string.
let consumption = Double(self.txtConsumption.text ?? "") ?? 0
Upvotes: 2