What does Fatal error Unexpectedly found nil while unwrapping an Optional value mean

Mistake producing Gemini contented Question & Answer :

My Swift programme is crashing with EXC_BAD_INSTRUCTION and 1 of the pursuing akin errors. What does this mistake average, and however bash I hole it?

Deadly mistake: Unexpectedly recovered nil piece unwrapping an Optionally available worth

oregon

Deadly mistake: Unexpectedly recovered nil piece implicitly unwrapping an Elective worth


This station is supposed to cod solutions to “unexpectedly recovered nil” points, truthful that they are not scattered and difficult to discovery. Awareness escaped to adhd your ain reply oregon edit the present wiki reply.

Inheritance: What’s an Non-obligatory?

Successful Swift, Optionally available<Wrapped> is an action kind: it tin incorporate immoderate worth from the first (“Wrapped”) kind, oregon nary worth astatine each (the particular worth nil). An optionally available worth essential beryllium unwrapped earlier it tin beryllium utilized.

Optionally available is a generic kind, which means that Non-obligatory<Int> and Elective<Drawstring> are chiseled sorts — the kind wrong <> is known as the Wrapped kind. Nether the hood, an Optionally available is an enum with 2 instances: .any(Wrapped) and .no, wherever .no is equal to nil.

Optionals tin beryllium declared utilizing the named kind Optionally available<T>, oregon (about generally) arsenic a shorthand with a ? suffix.

var anInt: Int = forty two var anOptionalInt: Int? = forty two var anotherOptionalInt: Int? // `nil` is the default once nary worth is supplied var aVerboseOptionalInt: Elective<Int> // equal to `Int?` anOptionalInt = nil // present this adaptable incorporates nil alternatively of an integer 

Optionals are a elemental but almighty implement to explicit your assumptions piece penning codification. The compiler tin usage this accusation to forestall you from making errors. From The Swift Programming Communication:

Swift is a kind-harmless communication, which means the communication helps you to beryllium broad astir the sorts of values your codification tin activity with. If portion of your codification requires a Drawstring, kind condition prevents you from passing it an Int by error. Likewise, kind condition prevents you from by chance passing an optionally available Drawstring to a part of codification that requires a non-non-compulsory Drawstring. Kind condition helps you drawback and hole errors arsenic aboriginal arsenic imaginable successful the improvement procedure.

Any another programming languages besides person generic action varieties: for illustration, Possibly successful Haskell, action successful Rust, and non-obligatory successful C++17.

Successful programming languages with out action varieties, a peculiar “sentinel” worth is frequently utilized to bespeak the lack of a legitimate worth. Successful Nonsubjective-C, for illustration, nil (the null pointer) represents the deficiency of an entity. For primitive varieties specified arsenic int, a null pointer tin’t beryllium utilized, truthful you would demand both a abstracted adaptable (specified arsenic worth: Int and isValid: Bool) oregon a designated sentinel worth (specified arsenic -1 oregon INT_MIN). These approaches are mistake-inclined due to the fact that it’s casual to bury to cheque isValid oregon to cheque for the sentinel worth. Besides, if a peculiar worth is chosen arsenic the sentinel, that means it tin nary longer beryllium handled arsenic a legitimate worth.

Action sorts specified arsenic Swift’s Elective lick these issues by introducing a particular, abstracted nil worth (truthful you don’t person to designate a sentinel worth), and by leveraging the beardown kind scheme truthful the compiler tin aid you retrieve to cheque for nil once essential.


Wherefore did I acquire “Deadly mistake: Unexpectedly recovered nil piece unwrapping an Elective worth”?

Successful command to entree an non-compulsory’s worth (if it has 1 astatine each), you demand to unwrap it. An elective worth tin beryllium unwrapped safely oregon forcibly. If you unit-unwrap an non-compulsory, and it didn’t person a worth, your programme volition clang with the supra communication.

Xcode volition entertainment you the clang by highlighting a formation of codification. The job happens connected this formation.

crashed line

This clang tin happen with 2 antithetic sorts of unit-unwrap:

1. Express Unit Unwrapping

This is accomplished with the ! function connected an elective. For illustration:

fto anOptionalString: Drawstring? mark(anOptionalString!) // <- Clang 

Deadly mistake: Unexpectedly recovered nil piece unwrapping an Optionally available worth

Arsenic anOptionalString is nil present, you volition acquire a clang connected the formation wherever you unit unwrap it.

2. Implicitly Unwrapped Optionals

These are outlined with a !, instead than a ? last the kind.

var optionalDouble: Treble! // this worth is implicitly unwrapped wherever it's utilized 

These optionals are assumed to incorporate a worth. So each time you entree an implicitly unwrapped optionally available, it volition mechanically beryllium unit unwrapped for you. If it doesn’t incorporate a worth, it volition clang.

mark(optionalDouble) // <- Clang 

Deadly mistake: Unexpectedly recovered nil piece implicitly unwrapping an Optionally available worth

Successful command to activity retired which adaptable induced the clang, you tin clasp ⌄ piece clicking to entertainment the explanation, wherever you mightiness discovery the optionally available kind.

IBOutlets, successful peculiar, are normally implicitly unwrapped optionals. This is due to the fact that your xib oregon storyboard volition nexus ahead the retailers astatine runtime, last initialization. You ought to so guarantee that you’re not accessing retailers earlier they’re loaded successful. You besides ought to cheque that the connections are accurate successful your storyboard/xib record, other the values volition beryllium nil astatine runtime, and so clang once they are implicitly unwrapped. Once fixing connections, attempt deleting the strains of codification that specify your shops, past reconnect them.


Once ought to I always unit unwrap an Non-compulsory?

Express Unit Unwrapping

Arsenic a broad regulation, you ought to ne\’er explicitly unit unwrap an non-obligatory with the ! function. Location whitethorn beryllium circumstances wherever utilizing ! is acceptable – however you ought to lone always beryllium utilizing it if you are one hundred% certain that the optionally available incorporates a worth.

Piece location whitethorn beryllium an juncture wherever you tin usage unit unwrapping, arsenic you cognize for a information that an non-obligatory accommodates a worth – location is not a azygous spot wherever you can’t safely unwrap that optionally available alternatively.

Implicitly Unwrapped Optionals

These variables are designed truthful that you tin defer their duty till future successful your codification. It is your duty to guarantee they person a worth earlier you entree them. Nevertheless, due to the fact that they affect unit unwrapping, they are inactive inherently unsafe – arsenic they presume your worth is non-nil, equal although assigning nil is legitimate.

You ought to lone beryllium utilizing implicitly unwrapped optionals arsenic a past hotel. If you tin usage a lazy adaptable, oregon supply a default worth for a adaptable – you ought to bash truthful alternatively of utilizing an implicitly unwrapped elective.

Nevertheless, location are a fewer eventualities wherever implicitly unwrapped optionals are generous, and you are inactive capable to usage assorted methods of safely unwrapping them arsenic listed beneath – however you ought to ever usage them with owed warning.


However tin I safely woody with Optionals?

The easiest manner to cheque whether or not an elective comprises a worth, is to comparison it to nil.

if anOptionalInt != nil { mark("Comprises a worth!") } other { mark("Doesn’t incorporate a worth.") } 

Nevertheless, ninety nine.9% of the clip once running with optionals, you’ll really privation to entree the worth it comprises, if it accommodates 1 astatine each. To bash this, you tin usage Optionally available Binding.

Elective Binding

Non-compulsory Binding permits you to cheque if an non-compulsory incorporates a worth – and permits you to delegate the unwrapped worth to a fresh adaptable oregon changeless. It makes use of the syntax if fto x = anOptional {...} oregon if var x = anOptional {...}, relying if you demand to modify the worth of the fresh adaptable last binding it.

For illustration:

if fto figure = anOptionalInt { mark("Comprises a worth! It is \(figure)!") } other { mark("Doesn’t incorporate a figure") } 

What this does is archetypal cheque that the optionally available incorporates a worth. If it does, past the ‘unwrapped’ worth is assigned to a fresh adaptable (figure) – which you tin past freely usage arsenic if it had been non-optionally available. If the optionally available doesn’t incorporate a worth, past the other clause volition beryllium invoked, arsenic you would anticipate.

What’s neat astir non-obligatory binding, is you tin unwrap aggregate optionals astatine the aforesaid clip. You tin conscionable abstracted the statements with a comma. The message volition win if each the optionals have been unwrapped.

var anOptionalInt : Int? var anOptionalString : Drawstring? if fto figure = anOptionalInt, fto matter = anOptionalString { mark("anOptionalInt comprises a worth: \(figure). And truthful does anOptionalString, it’s: \(matter)") } other { mark("1 oregon much of the optionals don’t incorporate a worth") } 

Different neat device is that you tin besides usage commas to cheque for a definite information connected the worth, last unwrapping it.

if fto figure = anOptionalInt, figure > zero { mark("anOptionalInt comprises a worth: \(figure), and it’s larger than zero!") } 

The lone drawback with utilizing elective binding inside an if message, is that you tin lone entree the unwrapped worth from inside the range of the message. If you demand entree to the worth from extracurricular of the range of the message, you tin usage a defender message.

A defender message permits you to specify a information for occurrence – and the actual range volition lone proceed executing if that information is met. They are outlined with the syntax defender information other {...}.

Truthful, to usage them with an elective binding, you tin bash this:

defender fto figure = anOptionalInt other { instrument } 

(Line that inside the defender assemblage, you essential usage 1 of the power transportation statements successful command to exit the range of the presently executing codification).

If anOptionalInt incorporates a worth, it volition beryllium unwrapped and assigned to the fresh figure changeless. The codification last the defender volition past proceed executing. If it doesn’t incorporate a worth – the defender volition execute the codification inside the brackets, which volition pb to transportation of power, truthful that the codification instantly last volition not beryllium executed.

The existent neat happening astir defender statements is the unwrapped worth is present disposable to usage successful codification that follows the message (arsenic we cognize that early codification tin lone execute if the non-compulsory has a worth). This is a large for eliminating ‘pyramids of doom’ created by nesting aggregate if statements.

For illustration:

defender fto figure = anOptionalInt other { instrument } mark("anOptionalInt comprises a worth, and it’s: \(figure)!") 

Guards besides activity the aforesaid neat tips that the if message supported, specified arsenic unwrapping aggregate optionals astatine the aforesaid clip and utilizing the wherever clause.

Whether or not you usage an if oregon defender message wholly relies upon connected whether or not immoderate early codification requires the non-obligatory to incorporate a worth.

Nil Coalescing Function

The Nil Coalescing Function is a nifty shorthand interpretation of the ternary conditional function, chiefly designed to person optionals to non-optionals. It has the syntax a ?? b, wherever a is an non-obligatory kind and b is the aforesaid kind arsenic a (though normally non-non-compulsory).

It basically lets you opportunity “If a accommodates a worth, unwrap it. If it doesn’t past instrument b alternatively”. For illustration, you may usage it similar this:

fto figure = anOptionalInt ?? zero 

This volition specify a figure changeless of Int kind, that volition both incorporate the worth of anOptionalInt, if it incorporates a worth, oregon zero other.

It’s conscionable shorthand for:

fto figure = anOptionalInt != nil ? anOptionalInt! : zero 

Non-obligatory Chaining

You tin usage Non-obligatory Chaining successful command to call a methodology oregon entree a place connected an non-obligatory. This is merely accomplished by suffixing the adaptable sanction with a ? once utilizing it.

For illustration, opportunity we person a adaptable foo, of kind an non-obligatory Foo case.

var foo : Foo? 

If we needed to call a methodology connected foo that doesn’t instrument thing, we tin merely bash:

foo?.doSomethingInteresting() 

If foo incorporates a worth, this technique volition beryllium referred to as connected it. If it doesn’t, thing atrocious volition hap – the codification volition merely proceed executing.

(This is akin behaviour to sending messages to nil successful Nonsubjective-C)

This tin so besides beryllium utilized to fit properties arsenic fine arsenic call strategies. For illustration:

foo?.barroom = Barroom() 

Once more, thing atrocious volition hap present if foo is nil. Your codification volition merely proceed executing.

Different neat device that elective chaining lets you bash is cheque whether or not mounting a place oregon calling a methodology was palmy. You tin bash this by evaluating the instrument worth to nil.

(This is due to the fact that an elective worth volition instrument Void? instead than Void connected a technique that doesn’t instrument thing)

For illustration:

if (foo?.barroom = Barroom()) != nil { mark("barroom was fit efficiently") } other { mark("barroom wasn’t fit efficiently") } 

Nevertheless, issues go a small spot much tough once making an attempt to entree properties oregon call strategies that instrument a worth. Due to the fact that foo is optionally available, thing returned from it volition besides beryllium non-compulsory. To woody with this, you tin both unwrap the optionals that acquire returned utilizing 1 of the supra strategies – oregon unwrap foo itself earlier accessing strategies oregon calling strategies that instrument values.

Besides, arsenic the sanction suggests, you tin ‘concatenation’ these statements unneurotic. This means that if foo has an elective place baz, which has a place qux – you may compose the pursuing:

fto optionalQux = foo?.baz?.qux 

Once more, due to the fact that foo and baz are elective, the worth returned from qux volition ever beryllium an optionally available careless of whether or not qux itself is non-compulsory.

representation and flatMap

An frequently underused characteristic with optionals is the quality to usage the representation and flatMap capabilities. These let you to use non-non-obligatory transforms to non-obligatory variables. If an non-obligatory has a worth, you tin use a fixed translation to it. If it doesn’t person a worth, it volition stay nil.

For illustration, fto’s opportunity you person an non-compulsory drawstring:

fto anOptionalString:Drawstring? 

By making use of the representation relation to it – we tin usage the stringByAppendingString relation successful command to concatenate it to different drawstring.

Due to the fact that stringByAppendingString takes a non-non-compulsory drawstring statement, we can not enter our non-compulsory drawstring straight. Nevertheless, by utilizing representation, we tin usage let stringByAppendingString to beryllium utilized if anOptionalString has a worth.

For illustration:

var anOptionalString:Drawstring? = "barroom" anOptionalString = anOptionalString.representation {unwrappedString successful instrument "foo".stringByAppendingString(unwrappedString) } mark(anOptionalString) // Optionally available("foobar") 

Nevertheless, if anOptionalString doesn’t person a worth, representation volition instrument nil. For illustration:

var anOptionalString:Drawstring? anOptionalString = anOptionalString.representation {unwrappedString successful instrument "foo".stringByAppendingString(unwrappedString) } mark(anOptionalString) // nil 

flatMap plant likewise to representation, but it permits you to instrument different optionally available from inside the closure assemblage. This means you tin enter an elective into a procedure that requires a non-non-obligatory enter, however tin output an non-compulsory itself.

attempt!

Swift’s mistake dealing with scheme tin beryllium safely utilized with Bash-Attempt-Drawback:

bash { fto consequence = attempt someThrowingFunc() } drawback { mark(mistake) } 

If someThrowingFunc() throws an mistake, the mistake volition beryllium safely caught successful the drawback artifact.

The mistake changeless you seat successful the drawback artifact has not been declared by america - it’s routinely generated by drawback.

You tin besides state mistake your self, it has the vantage of being capable to formed it to a utile format, for illustration:

bash { fto consequence = attempt someThrowingFunc() } drawback fto mistake arsenic NSError { mark(mistake.debugDescription) } 

Utilizing attempt this manner is the appropriate manner to attempt, drawback and grip errors coming from throwing capabilities.

Location’s besides attempt? which absorbs the mistake:

if fto consequence = attempt? someThrowingFunc() { // chill } other { // grip the nonaccomplishment, however location's nary mistake accusation disposable } 

However Swift’s mistake dealing with scheme besides gives a manner to “unit attempt” with attempt!:

fto consequence = attempt! someThrowingFunc() 

The ideas defined successful this station besides use present: if an mistake is thrown, the exertion volition clang.

You ought to lone always usage attempt! if you tin be that its consequence volition ne\’er neglect successful your discourse - and this is precise uncommon.

About of the clip you volition usage the absolute Bash-Attempt-Drawback scheme - and the non-compulsory 1, attempt?, successful the uncommon instances wherever dealing with the mistake is not crucial.


Assets