Sam Shaikh
Sam Shaikh

Reputation: 1646

Error: unexpectedly found nil while unwrapping an Optional value. How to solve it?

I views many posts like this, tried few things, but I couldn't get reason of error, neither I could solve it.

I have a custom Class.

class Profile: NSObject {
    var PlayerID: Int? = 0
   }

I have object in AppDelegate, for this class

var profile: Profile!

In some other class, I am using

if let playerID = appDelegate.profile.PlayerID {

}

It gives error

fatal error: unexpectedly found nil while unwrapping an Optional value

What is reason of this error. How to solve it.

What I tried

if let playerID = appDelegate.profile.PlayerID as? Int {

}

also I tried

if let playerID = appDelegate.profile.PlayerID as Int! {

  }

Thanks.

Upvotes: 0

Views: 212

Answers (2)

Elliott Minns
Elliott Minns

Reputation: 2784

The problem is your:

var profile: Profile! 

I'm assuming that profile is actually nil when you call this line:

if let playerID = appDelegate.profile.PlayerID {

}

Using the ! operator forces an object to be unwrapped, which can cause a runtime error if the object is nil when being accessed.

To be safe, you should change your profile property in the AppDelegate to:

var profile: Profile?

and then use optional chaining in to unwrap the object if it exists:

if let playerID = appDelegate.profile?.PlayerID {

}

If the profile object exists in the AppDelegate, this this will return the PlayerID, otherwise it will return nil and the code block won't be executed. You need to make sure you are assigning the profile to the AppDelegate as well at some point.

It's generally good practice to not use implicitly unwrapped properties unless you can absolutely guarantee that it will not be nil. (Which in most cases, is unlikely)

I hope this helps.

Upvotes: 4

Max Komarychev
Max Komarychev

Reputation: 2856

This error may occur in 3 points in your code

  1. if appDelegate is nil
  2. if profile is nil
  3. if playerID is nil

Try:

if let playerID = appDelegate?.profile?.PlayerID {

}

You may need to read more about optionals in swift and optional chaining

Upvotes: 1

Related Questions