Noe
Noe

Reputation: 56

How to accept input of a Double from a UITextField, and assign value to variable?

I put in comments asking my questions. Do the first 3 lines have to be weak? and how do i get var wage and var hours to equal the text boxes.

@IBOutlet var wageIn: UITextField! //does this need to be weak
@IBOutlet var hoursIn: UITextField!//does this need to be weak
@IBOutlet var payOut: UILabel! //does this need to be weak
@IBAction func goButt(sender: AnyObject) {

    var wage: Double = //wageIn
    var hours: Double = //hoursIn
    var prePay: Double = wage*hours


    let tax: Double = fitwCalc(prePay)  
    payOut.text = String(prePay - tax)
}

Upvotes: 2

Views: 130

Answers (1)

Nicolas Miari
Nicolas Miari

Reputation: 16246

How to accept input of a Double from a UITextField, and assign value to variable?

Something like this:

var myDoubleVariable:Double

if let text = textField.text {
    myDoubleVariable = Double(text) ?? 0.0
    // (Text may not represent valid double value e.g. the string "Hellow world!"); in 
    // which case the initialization will fail (return nil).
    // The code above falls back to "0.0" in such case.
}

//does this need to be weak

Not if the subview in question (UITextField in this case) is defined in a Storyboard: it is already strongly referenced by its parent view, so your outlet reference doesn't need to reference it strongly to prevent deallocation.

Upvotes: 1

Related Questions