Fatal error: unexpectedly found nil while unwrapping an Optional values
You can prevent the crash from happening by safely unwrapping cell.labelTitle
with an if let
statement.
if let label = cell.labelTitle{
label.text = "This is a title"
}
You will still have to do some debugging to see why you are getting a nil value there though.
Check if the cell is being registered with self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String)
. If so, then remove that line of code.
See this answer for more info: Why is UICollectionViewCell's outlet nil?
"If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard."
Almost certainly, your reuse identifier "title"
is incorrect.
We can see from the UITableView.h
method signature of dequeueReusableCellWithIdentifier
that the return type is an Implicitly Unwrapped Optional:
func dequeueReusableCellWithIdentifier(identifier: String!) -> AnyObject! // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
That's determined by the exclamation mark after AnyObject
:
AnyObject!
So, first thing to consider is, what is an "Implicitly Unwrapped Optional"?
The Swift Programming Language tells us:
Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.
These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.
So, basically, something that might have been nil at one point, but which from some point on is never nil again. We therefore save ourselves some bother by taking it in as the unwrapped value.
It makes sense in this case for dequeueReusableCellWithIdentifier
to return such a value. The supplied identifier must have already been used to register the cell for reuse. Supply an incorrect identifier, the dequeue can't find it, and the runtime returns a nil that should never happen. It's a fatal error, the app crashes, and the Console output gives:
fatal error: unexpectedly found nil while unwrapping an Optional value
Bottom line: check your cell reuse identifier specified in the .storyboard, Xib, or in code, and ensure that it is correct when dequeuing.