My Swift regime is crashing through EXC_BAD_INSTRUCTION and also one of the following similar errors. What does this error mean, and how carry out I settle it?

Fatal error: Unexpectedly discovered nil while unwrapping one Optional worth

or

Fatal error: Unexpectedly found nil if implicitly unwrapping an Optional value

This write-up is plan to collect answers come "unexpectedly found nil" issues, so that they space not scattered and also hard come find. Feel cost-free to include your very own answer or modify the present wiki answer.

You are watching: Thread 1: fatal error: unexpectedly found nil while unwrapping an optional value


This answer is ar wiki. If you feeling it might be made better, feel complimentary to modify it!

Background: those an Optional?

In Swift, Optional is an alternative type: it can contain any kind of value native the initial ("Wrapped") type, or no worth at every (the special value nil). An optional value should be unwrapped before it can be used.

Optional is a generic type, which means that Optional and Optional room distinct species — the kind inside is referred to as the wrapped type. Under the hood, an Optional is one enum v two cases: .some(Wrapped) and also .none, whereby .none is identical to nil.

Optionals can be declared using the named type Optional, or (most commonly) together a shorthand through a ? suffix.

var anInt: Int = 42var anOptionalInt: Int? = 42var anotherOptionalInt: Int? // `nil` is the default once no value is providedvar aVerboseOptionalInt: Optional // identical to `Int?`anOptionalInt = nil // currently this variable contains nil instead of one integerOptionals room a straightforward yet powerful tool come express your assumptions while writing code. The compiler can use this information to prevent you from making mistakes. From The Swift Programming Language:

Swift is a type-safe language, which method the language helps you to be clear about the species of worths your code have the right to work with. If component of her code calls for a String, kind safety avoids you indigenous passing that an Int by mistake. Likewise, form safety avoids you from accidentally pass an optional String to a item of password that requires a non-optional String. form safety helps you catch and fix errors as early as feasible in the advancement process.

Some various other programming languages also have generic alternative types: for example, perhaps in Haskell, option in Rust, and optional in C++17.

In programming language without option types, a details "sentinel" value is regularly used to show the lack of a precious value. In Objective-C, because that example, nil (the null pointer) to represent the absence of an object. Because that primitive varieties such together int, a null pointer can"t be used, so friend would require either a different variable (such as value: Int and isValid: Bool) or a designated sentinel worth (such as -1 or INT_MIN). These viewpoints are error-prone because it"s straightforward to forget to inspect isValid or to check for the sentinel value. Also, if a certain value is liked as the sentinel, that way it can no much longer be treated together a valid value.

Option varieties such as Swift"s Optional solve these troubles by introducing a special, separate nil worth (so you don"t have to designate a sentinel value), and by leveraging the strong form system for this reason the compiler can help you remember to inspect for nil once necessary.

Why walk I gain “Fatal error: Unexpectedly discovered nil while unwrapping an Optional value”?

In bespeak to accessibility an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If girlfriend force-unwrap an optional, and also it didn"t have actually a value, your regime will crash v the over message.

Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.

*

This crash can occur with two different kinds of force-unwrap:

1. Explicit force Unwrapping

This is done through the ! operator on an optional. For example:

let anOptionalString: String?print(anOptionalString!) // deadly error: Unexpectedly discovered nil if unwrapping one Optional value

As anOptionalString is nil here, you will get a crash top top the line whereby you pressure unwrap it.

2. Implicitly Unwrapped Optionals

These are identified with a !, rather than a ? after ~ the type.

var optionalDouble: Double! // this value is implicitly unwrapped where it"s usedThese optionals are assumed come contain a value. Thus whenever you access an implicitly unwrapped optional, the will immediately be pressure unwrapped because that you. If it no contain a value, it will crash.

print(optionalDouble) // deadly error: Unexpectedly uncovered nil while implicitly unwrapping an Optional value

In stimulate to occupational out i m sorry variable caused the crash, you have the right to hold ⌥ while clicking to show the definition, wherein you could find the optional type.

*

IBOutlets, in particular, are usually implicitly unwrapped optionals. This is since your xib or storyboard will connect up the outlets at runtime, after initialization. You should as such ensure the you’re not accessing outlets prior to they"re invited in. You likewise should examine that the relations are exactly in her storyboard/xib file, otherwise the values will it is in nil at runtime, and therefore crash when they room implicitly unwrapped. When fixing connections, shot deleting the present of password that define your outlets, climate reconnect them.

When should I ever force unwrap an Optional?

Explicit pressure Unwrapping

As a basic rule, you should never explicitly force unwrap one optional through the ! operator. There may be situations where using ! is acceptable – but you need to only ever before be utilizing it if you are 100% sure that the optional consists of a value.

While over there may be an occasion wherein you deserve to use force unwrapping, as you know for a fact that an optional consists of a worth – over there is no a single location where you can not safely unwrap that optional instead.

Implicitly Unwrapped Optionals

These variables space designed so that you have the right to defer their assignment until later on in your code. The is your responsibility to certain they have a value prior to you access them. However, because they involve pressure unwrapping, they space still inherently unsafe – together they assume your worth is non-nil, even though assigning nil is valid.

You must only be using implicitly unwrapped optionals together a last resort. If you deserve to use a lazy variable, or administer a default value for a variable – you must do so instead of utilizing an implicitly unwrapped optional.

However, there are a couple of scenarios where implicitly unwrapped optionals space beneficial, and you are still able to usage various means of safely unwrapping them as provided below – yet you should always usage them through due caution.

How deserve to I safely attend to Optionals?

The simplest means to inspect whether one optional contains a value, is to compare it to nil.

if anOptionalInt != nil print("Contains a value!") rather print("Doesn’t save a value.")However, 99.9% the the time when working with optionals, you will do it actually want to access the worth it contains, if it consists of one in ~ all. To carry out this, you can use Optional Binding.

Optional Binding

Optional Binding allows you to inspect if an optional consists of a value – and allows you to assign the unwrapped value to a new variable or constant. It supplies the syntax if allow x = anOptional ... Or if var x = anOptional ..., escape if you should modify the value of the new variable after ~ binding it.

For example:

if let number = anOptionalInt print("Contains a value! that is \(number)!") rather print("Doesn’t contain a number")What this does is an initial check the the optional consists of a value. If it does, then the ‘unwrapped’ value is assigned come a new variable (number) – i m sorry you have the right to then easily use together if it were non-optional. If the optional doesn’t save on computer a value, climate the rather clause will certainly be invoked, together you would certainly expect.

What’s neat about optional binding, is you have the right to unwrap lot of optionals at the same time. You can just separate the statements through a comma. The statement will succeed if all the optionals to be unwrapped.

var anOptionalInt : Int?var anOptionalString : String?if allow number = anOptionalInt, let text = anOptionalString print("anOptionalInt has a value: \(number). And so go anOptionalString, it’s: \(text)") rather print("One or an ext of the optionals don’t contain a value")Another neat cheat is that you can also use commas to inspect for a particular condition ~ above the value, ~ unwrapping it.

if allow number = anOptionalInt, number > 0 print("anOptionalInt has a value: \(number), and also it’s greater than zero!")The only record with utilizing optional binding within an if statement, is the you deserve to only access the unwrapped value from in ~ the border of the statement. If girlfriend need access to the value from outside of the scope of the statement, you have the right to use a guard statement.

A safety statement permits you to define a condition for success – and also the current scope will only proceed executing if that condition is met. They are identified with the syntax guard problem else ....

So, to usage them through an optional binding, you can do this:

guard allow number = anOptionalInt else return(Note the within the security body, friend must use among the manage transfer declaration in bespeak to departure the border of the currently executing code).

If anOptionalInt has a value, it will certainly be unwrapped and also assigned come the new number constant. The code after the guard will then proceed executing. If it doesn’t contain a value – the guard will execute the password within the brackets, i beg your pardon will cause transfer of control, so the the code immediately after will certainly not be executed.

The genuine neat thing around guard explanation is the unwrapped value is now easily accessible to use in code that follows the explain (as we recognize that future code deserve to only execute if the optional has a value). This is a great for remove ‘pyramids of doom’ developed by nesting many if statements.

For example:

guard let number = anOptionalInt rather returnprint("anOptionalInt has a value, and also it’s: \(number)!")Guards additionally support the same neat tricks the the if statement supported, such as unwrapping many optionals in ~ the exact same time and using the wherein clause.

Whether you use an if or safety statement totally depends top top whether any kind of future password requires the optional to contain a value.

Nil Coalescing Operator

The Nil Coalescing Operator is a nifty shorthand variation of the ternary conditional operator, generally designed to convert optionals come non-optionals. It has actually the syntax a ?? b, whereby a is one optional type and b is the same form as a (although usually non-optional).

It basically lets you speak “If a contains a value, unwrap it. If the doesn’t then return b instead”. Because that example, you might use it like this:

let number = anOptionalInt ?? 0This will define a number consistent of Int type, that will either contain the worth of anOptionalInt, if it consists of a value, or 0 otherwise.

It’s just shorthand for:

let number = anOptionalInt != nil ? anOptionalInt! : 0

Optional Chaining

You deserve to use Optional Chaining in order to call a method or accessibility a residential or commercial property on one optional. This is simply done by suffixing the change name v a ? once using it.

For example, to speak we have a change foo, of kind an optional Foo instance.

var foo : Foo?If we want to contact a technique on foo that doesn’t return anything, we deserve to simply do:

foo?.doSomethingInteresting()If foo has a value, this method will be dubbed on it. If it doesn’t, nothing negative will occur – the code will certainly simply continue executing.

(This is similar behaviour to sending messages come nil in Objective-C)

This can therefore additionally be used to set properties and call methods. Because that example:

foo?.bar = Bar()Again, nothing poor will happen here if foo is nil. Your code will simply continue executing.

Another practiced trick the optional chaining lets you carry out is examine whether setup a building or phone call a an approach was successful. You have the right to do this by compare the return worth to nil.

(This is due to the fact that an optional value will return Void? fairly than Void on a an approach that doesn’t return anything)

For example:

if (foo?.bar = Bar()) != nil print("bar was set successfully") rather print("bar wasn’t set successfully")However, things become a little bit an ext tricky once trying to accessibility properties or contact methods that return a value. Due to the fact that foo is optional, anything reverted from the will additionally be optional. To deal with this, you have the right to either unwrap the optionals that gain returned using one of the above methods – or unwrap foo itself prior to accessing approaches or calling methods that return values.

Also, together the surname suggests, you can ‘chain’ these statements together. This way that if foo has an optional building baz, which has actually a building qux – you could write the following:

let optionalQux = foo?.baz?.quxAgain, because foo and also baz space optional, the value went back from qux will constantly be an optional regardless of even if it is qux chin is optional.

map and flatMap

An regularly underused feature with optionals is the ability to use the map and flatMap functions. These enable you to use non-optional transforms to optional variables. If an optional has actually a value, girlfriend can apply a given revolution to it. If that doesn’t have actually a value, it will remain nil.

For example, let’s say you have actually an optional string:

let anOptionalString:String?By applying the map role to that – we have the right to use the stringByAppendingString role in order to concatenate that to one more string.

Because stringByAppendingString bring away a non-optional string argument, us cannot input ours optional wire directly. However, by making use of map, we deserve to use allow stringByAppendingString come be supplied if anOptionalString has actually a value.

For example:

var anOptionalString:String? = "bar"anOptionalString = anOptionalString.map unwrappedString in return "foo".stringByAppendingString(unwrappedString)print(anOptionalString) // Optional("foobar")However, if anOptionalString doesn’t have a value, map will return nil. For example:

var anOptionalString:String?anOptionalString = anOptionalString.map unwrappedString in return "foo".stringByAppendingString(unwrappedString)print(anOptionalString) // nilflatMap works likewise to map, other than it allows you come return another optional from in ~ the closure body. This means you have the right to input one optional right into a procedure that calls for a non-optional input, however can calculation an optional itself.

try!

Swift"s error managing system have the right to be safely supplied with Do-Try-Catch:

do let result = shot someThrowingFunc() capture print(error)If someThrowingFunc() litter an error, the error will certainly be safely recorded in the capture block.

The error consistent you view in the record block has not been declared by us - it"s immediately generated by catch.

You can likewise declare error yourself, it has the advantage of gift able to cast it to a beneficial format, because that example:

do let an outcome = shot someThrowingFunc() catch let error as NSError print(error.debugDescription)Using try this way is the proper way to try, catch and also handle errors coming from throw functions.

There"s likewise try? i beg your pardon absorbs the error:

if let result = try? someThrowingFunc() // cool rather // take care of the failure, yet there"s no error info availableBut Swift"s error managing system likewise provides a means to "force try" with try!:

let an outcome = try! someThrowingFunc()The concepts explained in this post likewise apply here: if one error is thrown, the application will certainly crash.

You must only ever use try! if you can prove that its an outcome will never fail in your context - and also this is really rare.

See more: Helms Deep: Server Is Enforcing Consistency For This File Consistency

Most of the moment you will use the finish Do-Try-Catch system - and also the optional one, try?, in the rare situations where managing the error is not important.