Application crashes on device – works perfectly on Simulator

i0S Swift Issue

Question or problem in the Swift programming language:

Recently, I have been working on an application. The goal of the application is to show you your last 10 photos taken in the Today view of the Notification Center, among other things. The application works perfectly in the iOS Simulator, but as soon as I put it on a real device for testing, it fails. It returns the error:

fatal error: Unexpected nil while unwrapping an Optional value

Typically this is very easy to fix since XCode highlights the code that returned nil and gives you the opportunity to fix it. In this case, none of my code gets highlighted. Instead, it highlights a line from Thread 1 (Is this the correct term? Thread 1?), as seen below:

Also note that above the highlited line is the line

; function signature specialization  ()).(closure #2)

I included this line in the picture because of the “fatalErrorMessage” part of it. I suspect this could clue me in on the error, but I have no idea what this means. I’m not yet to the point of understanding that.

Also, after some thought, I placed a breakpoint at the viewDidLoad() function in the hopes of tracking any nil values, but the code appears to never even get to this point. It seems as if none of my code is being run.

Has anyone had problems like this/understands what that error code (If that’s what it is) means? I’m pretty desperate now, hence me being here.


I placed a println line inside the viewDidLoad function to double check if it was being run. The println function runs and outputs correctly, so I think I may just have messed up my breakpoint somehow. Anyway – the code runs, but it still doesn’t highlight any of my code causing the nil value.

As requested, I have inserted parts of my code. Please keep in mind that this code is a “first draft”, if you will, and I have not yet gotten around to cleaning it up. I’m just trying to get it to work:

@IBOutlet weak var currentPosLabel: UILabel!
var currentImgPos = 0
@IBOutlet weak var imageView: UIImageView!
var images: NSMutableArray!
var totalImageCountNeeded: Int!

func fetchPhotos() {
    images = NSMutableArray()
    totalImageCountNeeded = 10

func fetchPhotoAtIndexFromEnd(index: Int) {
    let imgManager = PHImageManager.defaultManager()

    var requestOptions = PHImageRequestOptions()
    requestOptions.synchronous = true

    var fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    if let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions) {
        if fetchResult.count > 0 {
            imgManager.requestImageForAsset(fetchResult.objectAtIndex(fetchResult.count - 1 - index) as? PHAsset, targetSize: view.frame.size, contentMode: PHImageContentMode.AspectFill, options: requestOptions, resultHandler: { (image, _) in
                if index + 1 < fetchResult.count && self.images.count < self.totalImageCountNeeded {
                    self.fetchPhotoAtIndexFromEnd(index + 1)
                } else {
                    println("Completed array: \(self.images)")



override func viewDidLoad() {

override func viewDidAppear(animated: Bool) {
    // NOTE: I am calling the fetchPhotos() function here since earlier in my debugging I thought the problem may be that I was calling it too early in the viewDidLoad function. It an incorrect theory, but it was worth a try.
    if images.count > 0 {
        imageView.image = images[1] as? UIImage

I removed some parts of the code that I know have no reasons to cause my error, such as @IBActions, didReceiveMemoryWarning(), etc..

How to solve the problem:

Solution 1:

Even it’s old question. I found my issue by deleting derived data from xcode.

Xcode -> window->Projects then select and delete your project derived data.

Solution 2:

I don’t think it is possible to determine exactly where the problem is without seeing your code.

Somewhere in your code you may have forced downcast a variable as!. If you change this to:

if let variable = optionalVariable as? SomeClass {
    //Insert your code

Then this should fix your problem. Read this to learn more about casting in swift:

Solution 3:

You should run the same device on simulator and real device.As an example if you run on 5s on real device then try the same device on simulator.By running simulator, it will definitely show the error.My error was the not connecting the @IBActions. Hope that this tip will help you.

Solution 4:

I received the same error when trying to set a non-optional value to the value of an implicitly-unwrapped optional that was nil.

Ex. someGlobalFunction() returns an ImplicitlyUnwrappedOptional with a nil value then you try to set that to a regular value.

func someGlobalFunction() -> String! { return nil }

class MyClass {
    let aVariable: String

    init() {
        aVariable = someGlobalFunction()

Hope this helps!