rowenarrow
rowenarrow

Reputation: 67

Testing optional for nil and switching nil to 0

I am working on a simple app where I need to add two numbers entered in a text field together. I want to make it so that if on of the textfields doesn't have an entry in it, it will calculate as 0. What is the most efficient way to do this? Any help would be appreciated

@IBAction func myButton(sender: AnyObject) {

    //reveals label upon click of button
    myLabel1.hidden = false

    //textField constants
    let firstNum = Double(myTextField1.text!)
    let secondNum = Double(myTextField2.text!)


    let outputValue = Double(firstNum! + secondNum!)
    myLabel1.text = "Result: \(outputValue)"


}

Upvotes: 0

Views: 61

Answers (1)

Hamish
Hamish

Reputation: 80781

Use the nil coalescing operator (with a correction from vacawama):

let firstNum = Double(myTextField1.text ?? "") ?? 0
let secondNum = Double(myTextField2.text ?? "") ?? 0

Upvotes: 4

Related Questions