view raw
sebiraw sebiraw - 6 months ago 48
Swift Question

Thread 1: EXC_BAD_INSTRUCTION Issue with dismissing keyboard and nil values (.isNaN)

I'm making a calculator app that solves for the missing variable and I've added a piece of code that dismisses the keyboard by tapping anywhere on the screen or pressing the "return" key.

This function was working before I added the if else statements to check which variable was missing (using .isNaN) so that it could solve for that missing variable.

Here is my code for that specific view controller:

import UIKit

class findSpeed: UIViewController, UITextFieldDelegate {

@IBOutlet weak var vValue: UITextField!
@IBOutlet weak var dValue: UITextField!
@IBOutlet weak var tValue: UITextField!
@IBOutlet weak var answer: UILabel!

@IBAction func solve(_ sender: UIButton) {

let v = Float(vValue.text! as String);
let d = Float(dValue.text! as String);
let t = Float(tValue.text! as String);

let solvev = (d!/t!);
let solved = (v!*t!);
let solvet = (d!/v!);

if (v!.isNaN) {
answer.text = "Answer: \(solvev)"

else if (d!.isNaN) {
answer.text = "Answer: \(solved)"

else {
answer.text = "Answer: \(solvet)"


override func viewDidLoad() {
vValue.delegate = self;
dValue.delegate = self;
tValue.delegate = self;
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismiss")))

func dismiss() {

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true

override func didReceiveMemoryWarning() {

The error I'm receiving occurs when I tap the button that links to this view controller where the calculator is:
Picture of error


Use the debugger and see why the app is crashing. Clearly vValve is nil which means you didn't connect anything to the outlet in Interface Builder.

Fix your outlet connections and the error posted in your question will be fixed.

You also need to eliminate all of the forced unwrapping you are doing. Otherwise you are going to have a lot more crashes to deal with. I strongly urge you to review What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?