I've tried to read up on many of the postings before but I still seem to not be able to understand "nil".
let mass = Double(density! * volume!)
In this section of the code it tells me:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
When I run my app it runs smoothly if I don't press the button while all the text fields are empty but when I do it crashes and the debugger tool tells me the error is here but I'm not sure why it doesn't work.
I just really don't understand the other nil explanation forums on Stack Overflow and Swift is very confusing for me as it is.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var massInput: UITextField!
@IBOutlet weak var volumeInput: UITextField!
@IBOutlet weak var densityInput: UITextField!
@IBOutlet weak var answerOutput: UITextField!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func calculateButton(_ sender: UIButton) {
clearAnswer()
mvdCalc()
clearBoxes()
}//end of btn
//------------------------FUNCTIONS-----------------------------------
func mvdCalc(){
if massInput.text!.isEmpty {massFormula()}
if volumeInput.text!.isEmpty {volumeFormula()}
if densityInput.text!.isEmpty {densityFormula()}
}//end of mvdCalc
func clearBoxes(){
massInput.text = ""
volumeInput.text = ""
densityInput.text = ""
}//end of clear boxes
func massFormula(){
let density = Double(densityInput.text!)
let volume = Double(volumeInput.text!)
let mass = Double(density! * volume!)
answerOutput.text = "\(mass)"
}//end of mass
func volumeFormula(){
let density = Double(densityInput.text!)
let mass = Double(massInput.text!)
let volume = Double(mass! / density!)
answerOutput.text = "\(volume)"
}//end of volume
func densityFormula(){
let volume = Double(volumeInput.text!)
let mass = Double(massInput.text!)
let density = Double(mass! / volume!)
answerOutput.text = "\(density )"
}//end of density
func clearAnswer() {
if massInput.text == "" && volumeInput.text == "" && densityInput.text == "" {
answerOutput.text = ""
}
}//end of clearAnswer
}//end of class