yoadle yoadle - 4 years ago 448
Swift Question

Swift : fatal error: unexpectedly found nil and EXC_BAD_INSTRUCTION

I m new to Xcode and i m building a project with a login button. After clicking the login with details in the text field, it will redirect to the second view which is the scroll view controller. However, i got two parts of "Error" which is

Normally, it work with a normal view controller(login and move to the second view). I have just recreate a view controller to a scroll view controller and it did not work.

By the way, I got a build success but i just got error when i try to "login"

Can anyone explain why i got the thread error and the fatal error?
How can i resolve the problem?

login view Controller

@IBAction func LoginBtn(sender: AnyObject) {
LoginIn()
}

func LoginIn(){
let user = PFUser()
user.username = usernameTF.text!
user.password = passwordTF.text!

PFUser.logInWithUsernameInBackground(usernameTF.text!,
password:passwordTF.text! , block: { (User: PFUser?, Error
:NSError? ) -> Void in

if Error == nil{
dispatch_async(dispatch_get_main_queue()){

let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("scrollV") as UIViewController

self.presentViewController(MainVC, animated: true, completion: nil)

}
}
else{
NSLog("Wrong!!!!")
}
})
}


Scroll View Controller

import UIKit

class ScrollViewController: UIViewController {


@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
super.viewDidLoad()


let V1 : ScrollViewController = ScrollViewController(nibName: "ScrollViewController", bundle: nil)
self.addChildViewController(V1)
self.scrollView!.addSubview(V1.view!)
V1.didMoveToParentViewController(self)
}

Answer Source

You are doing some forced unwrapping, which is not recommended (in general forced stuff in Swift in not recommended), and it will crash your application if the variable being unwrapped is nil. That's why forced unwrap is recommended only when you're 100% sure that you have a valid value in your optional.

In your case, it seems that V1.view! causes the crash, and this might be caused by the fact that V1 didn't successfully loaded from the nib.

Swift has made it very easy to work with nullable values. Just don't force unwrap and use optional binding instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download