Hello, always when i try to run my app and press the button then i get this error. Can somebody help me? Thanks
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var calculatorLabel: UILabel!
var isTypingNumber = false
@IBAction func numberTapped(_ sender: UIButton) {
let number = sender.currentTitle!
if isTypingNumber {
calculatorLabel.text = calculatorLabel.text! + number
} else {
calculatorLabel.text = number
isTypingNumber = true
}
}
}
Welcome to the forum.
That's because currentTitle may be nil (depending on button state or because it has not yet been set).
You should write:
let number = sender.currentTitle ?? (sender.titleLabel?.text ?? "0") // In last resort, consider it is "0"
Note: It is always very risky to unwrap an optional without checking for nil. Unless you are absolutely sure it is not nil (which is usually hard to be).