-2

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"

Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
AR Tunes
  • 6
  • 3
  • what is the value of self.tfMobile.text? – PPL Mar 13 '18 at 07:18
  • And how you are sure about that a valid integer has been inserted in the `tfMobile`? obviously, if its text isn't a valid int no doubt you would get such an error. – Ahmad F Mar 13 '18 at 07:19
  • self.tfMobile.text is the text in the text field. – AR Tunes Mar 13 '18 at 07:19
  • when i print that string in ViewController2 then it shows correctly in the console. But when i convert this string into Int type, and print that then it shows an error (Unexpectedly found nil while unwrapping an optional value) – AR Tunes Mar 13 '18 at 07:20
  • You should never forcily unwrap an optional, it will cause a crash – Fahadsk Mar 13 '18 at 07:20
  • Replace `let numPhone = Int(strPhone)!` with `let numPhone = Int(strPhone)?` – Kuldeep Mar 13 '18 at 07:23
  • Change the order: First set `strPhone` in the controller, than push it. Basically the code crashes if the string cannot be converted to `Int`. An empty string as default value is nonsensical because it can **not** be converted to `Int` anyway. – vadian Mar 13 '18 at 07:25

1 Answers1

0

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)
}
Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34