juliano.net
juliano.net

Reputation: 8177

Can't set a variable to the value of a textfield

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

Answers (2)

Rey Bruno
Rey Bruno

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

David Pasztor
David Pasztor

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

Related Questions