Can anyone help: The code works on iOS simulator (iPhone 13mini) chrashes on real iPhone 13mini: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
I don't understand how "bill" can be nil since it was checked before actually unwrapping it.
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var billTextField: UITextField!
@IBOutlet weak var zeroPctButton: UIButton!
@IBOutlet weak var tenPctButton: UIButton!
@IBOutlet weak var twentyPctButton: UIButton!
@IBOutlet weak var splitNumberLabel: UILabel!
var tip = 0.10
var numberOfPeople = 2
var billTotal = 0.0
var finalResult = "0.0"
@IBAction func tipChanged(_ sender: UIButton) {
billTextField.endEditing(true)
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
let buttonTitle = sender.currentTitle!
let buttonTitleMinusPercentSign = String(buttonTitle.dropLast())
let buttonTitleAsANumber = Double(buttonTitleMinusPercentSign)!
tip = buttonTitleAsANumber / 100
}
@IBAction func stepperValueChanged(_ sender: UIStepper) {
splitNumberLabel.text = String(format: "%.0f", sender.value)
numberOfPeople = Int(sender.value)
}
@IBAction func calculatePressed(_ sender: UIButton) {
let bill = billTextField.text!
if bill != "" {
billTotal = Double(bill)!
let result = billTotal * (1 + tip) / Double(numberOfPeople)
finalResult = String(format: "%.2f", result)
}
self.performSegue(withIdentifier: "goToResults", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToResults" {
let destinationVC = segue.destination as! ResultsViewController
destinationVC.result = finalResult
destinationVC.tip = Int(tip * 100)
destinationVC.split = numberOfPeople
}
}
}
Thank you very much. I finally found the solution myself: The problem was that I was using an iPhone localized in Germany. Therefore the input
string
didn't have a dot but a comma as seperator (25.50 vs 25,50).So, I replaced the line
let bill = billTextField.text!
withlet bill = (billTextField.text?.replacingOccurrences(of: ",", with: "."))!
and it now works well. :-)