Your application is going to crash! A Cocoa application will usually crash for the following reasons:
When a crash happens, Xcode will attempt to give you as much information as it can in order to help you fix the issue. First, the system will highlight the offending line of code that caused the error in the standard editor. To the left, it will show the error type or code that caused it. In many cases, more information will be printed on the console.
The simplest way of crashing an application in Swift is by forcibly unwrapping an optional with a nil
value (EXC_BAD_INSTRUCTION
). Create a new, single view application called Crash
and save it on your Mac.
Open up ViewController.swift
and add the following lines of code:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let testConstant:String? = nil print(testConstant!) } }
Run the application and watch it immediately crash with the EXC_BAD_INSTRUCTION
error, like this:
The system highlights the line that caused the crash, and the information on the console hints at what crashed your app:
fatal error: unexpectedly found nil while unwrapping an Optional value
To fix the crash, simply remove the exclamation point from the print
statement, as follows:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let testConstant:String? = nil print(testConstant) } }
The app will run properly and nil
will be printed on the console, as shown in this screenshot:
3.145.143.239