When converting String to Int type and print that Int type in console then show an error

Unexpectedly found nil while unwraping an optional value

ViewController.swift

    @IBAction func btnVerifyOTP(_ sender: Any)
    {
          let verifyOTP = 
          self.storyboard?.instantiateViewController(withIdentifier: "VerifyOTP") as! VerifyOTP
          self.navigationController?.pushViewController(verifyOTP, animated: true)
          verifyOTP.strPhone = self.tfMobile.text!
    }

ViewController2.swift

class VerifyOTP: UIViewController {

var strPhone = String()

override func viewDidLoad() {
        super.viewDidLoad()

       let numPhone = Int(strPhone)!
       print(numPhone)
    }
}

Error : This method will print "Unexpectedly found nil while unwrapping an optional value"

1

There are 1 best solutions below

1
Andreas Oetjen On

One of your problems lies in the initialization order: What happens is thatviewDidLoad is executed before verifyOTP.strPhone = self.tfMobile.text! is executed (because of pushViewController).

This means that strPhone is an empty string, and Int(strPhone) returns nil, so forced unwrapping will crash.

You might want to change the execution order in btnVerifyOTP:

@IBAction func btnVerifyOTP(_ sender: Any)
{
    let verifyOTP = 
    self.storyboard?.instantiateViewController(withIdentifier: "VerifyOTP") as! VerifyOTP
    verifyOTP.strPhone = self.tfMobile.text!
    self.navigationController?.pushViewController(verifyOTP, animated: true)
}

You should also do some nil checking in your viewDidLoad:

if let numPhone = Int(strPhone) {
     print(numPhone)
}