Found nil while unwrapping optional value

You might think: "another post about this error". Yes, i've been looking into this forum before writing this question and unfortunately i couldn't find something that could help, or atleast i know that this error gets on when there is a var that is not bound.

However since im quite new into this, i'd like some help. I'm following a guide to make a simple infinite side scroller game. So far everything went good but then i encountered this "nill" error. The guide itself does not have this error.

So i tought maybe it could be that i use a newer version of xCode or iphone simulation. But im pretty sure its not about that.

My codings so far:

import Foundation

class MainScene: CCNode {
    weak var hero: CCSprite!

    func didLoadFromCCB() {
       userInteractionEnabled = true
    }

    override func touchesBegan(touch: CCTouch!, withEvent event: CCTouchEvent!) {
       // This is the error line. I think it is caused by (applyImpulse(ccp(0, 400)) )
        hero.physicsBody.applyImpulse(ccp(0, 400)) 
    }
}

How can i simply fix this? should i make a variable with applyImpulse? I also tried to switch between CGPoint (ccp) and CCPackage, both didn't worked.

Answers


  weak var hero: CCSprite!

This is incredibly dangerous and likely the cause of your problem. Besides using !, which is almost always to be avoided, this mixes it with weak. That means that if something else stops pointing to hero, this variable becomes an implicitly unwrapped nil. The next time you access it, you crash.

First, get rid of the !. If it needs to be weak, use ?. Beyond that, decide if it should really be strong. nothing you've shown here suggests that it should be weak.


I think the error code above can cause much confusion for new people because we don't know what is "optional" in swift 2.0 vs older versions of swift. For example I was getting the same error and could not tell where the problem was. What I found out is that I was making a call to a method using parenthesis () and in the same function I called the method without the parenthesis. This caused the error above. The () are an optional component that became optional with Swift 2.0 the way I understand it. You have to be consistent when calling the methods otherwise the compiler will throw the "Found nil error while unwrapping an optional value". Here is my code: The method I called inconsistently was NSDirectoryEnnumerationOptions(). This is corrected in the example I am sharing:

      func listFilesWithFilter() -> [String]
{
NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    let musicUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
    do{
        let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(musicUrl,includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
        print(fileList)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    // filter for wav files 
    do {
        let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(musicUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
        print(directoryUrls)
        let wavFiles = directoryUrls.filter(){ $0.pathExtension == "wav"}.map{ $0.lastPathComponent}
        print ("WavFiles:\n" + wavFiles.description)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    return wavFiles
    }  

Need Your Help

PHP: Inserting variables into template file - include() or file_get_contents()?

php variables templates

I'm working on a project where I'm keeping all HTML content separate from the rest of the PHP code. Each instance where any HTML needs to be parsed for PHP variables is sent through a function call...

Bad alloc is thrown

c++ memory boost bad-alloc

I am getting a 'bad_alloc while trying to work with boost managed shared memory. I've copied the boost example from their quick guide for the impatient and incorporated my own changes. MY code is b...