Totally can not figure out how to protect against a textfield that is nil, always crashing on dollarsTextField with Unexpectedly found nil while unwrapping an Optional value
Here’s what I have, any help would be great, thank you
import UIKit
class ViewController: UIViewController {
@IBOutlet var dollarsTextField: UITextField!
@IBOutlet var halvesTextField: UITextField!
@IBOutlet var quartersTextField: UITextField!
@IBOutlet var dimesTextField: UITextField!
@IBOutlet var nickelsTextField: UITextField!
@IBOutlet var penniesTextField: UITextField!
@IBOutlet var dollarLabel: UILabel!
@IBOutlet var halveLabel: UILabel!
@IBOutlet var quarterLabel: UILabel!
@IBOutlet var dimeLabel: UILabel!
@IBOutlet var nickelLabel: UILabel!
@IBOutlet var pennyLabel: UILabel!
@IBOutlet var valueLabel: UILabel!
@IBOutlet weak var coinLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func calculate(_ sender: Any) {
let a = Float(dollarsTextField.text!)!
let b = Float(halvesTextField.text!)! * 0.50
let c = Float(quartersTextField.text!)! * 0.25
let d = Float(dimesTextField.text!)! * 0.10
let e = Float(nickelsTextField.text!)! * 0.05
let f = Float(penniesTextField.text!)! * 0.01
let g = Float(dollarsTextField.text!)!
let h = Float(halvesTextField.text!)!
let i = Float(quartersTextField.text!)!
let j = Float(dimesTextField.text!)!
let k = Float(nickelsTextField.text!)!
let l = Float(penniesTextField.text!)!
dollarLabel.text = String(format:"%0.2f", a)
halveLabel.text = String(format:"%0.2f", b)
quarterLabel.text = String(format:"%0.2f", c)
dimeLabel.text = String(format:"%0.2f", d)
nickelLabel.text = String(format:"%0.2f", e)
pennyLabel.text = String(format:"%0.2f", f)
valueLabel.text = String(format: "%0.2f", a+b+c+d+e+f)
coinLabel.text = String(format: "%0.0f", g+h+i+j+k+l)
// Ive tried this and some other code, and Im at wits end!
// if dollarsTextField != nil {
// let output = String(format: "%0.2f", a)
// dollarLabel.text = "\(output)"
// } else {
// dollarLabel.text = "0"
// dollarsTextField.text = "0"
// }
if dollarsTextField == nil {
//dollarLabel.text = "0"
dollarsTextField.text = "0"
} else {
let output = String(format: "%0.0f", g)
dollarsTextField.text = "\(output)"
}
}
}