Mohammed
Mohammed

Reputation: 15

Converting a UITextField String to a Double inside a UITextField Action

I have not been able to convert hoursWorked to a double inside a UITextField property I keep getting a "Cannot invoke initializer for type 'Double' with an argument list of type '(UITextField!)'"

  @IBOutlet weak var hoursWorked: UITextField!

   @IBAction func onEditingChange(sender: UITextField) {
        var hoursWorkedAmount = Double(hoursWorked)
        var salary = hoursWorkedAmount! * 25
        print(salary)
    }

I've tried to test everything before hand on playgrounds to get a better understanding of what I'm doing wrong but I keep getting the error.

Upvotes: 0

Views: 921

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You need to get the text field's text, not the text field itself.

Change:

var hoursWorkedAmount = Double(hoursWorked)

to:

var hoursWorkedAmount = Double(hoursWorked.text)

Better yet, change it to:

var hoursWorkedAmount = Double(sender.text)

This way your method acts on the actual text field that sent the event.

Note: I'm not fluent in Swift. You might need a ! after text.

Upvotes: 2

Related Questions