129

I was using an UICollectionView in Swift but I get when I try to change the text of the cell's label.

    func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int
{
    return 5
}

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("title", forIndexPath: indexPath) as TitleCollectionViewCell
    // Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
    cell.labelTitle.text = "This is a title"
    return cell
}

Does anyone know about this?

Screenshot for warning on Console

Jack
  • 10,795
  • 4
  • 65
  • 90
rulilg
  • 1,564
  • 4
  • 14
  • 19
  • 5
    check `cell.labelTitle` is not `nil` – Bryan Chen Jul 09 '14 at 00:14
  • 5
    ... and that `cell` isn't `nil`, either. – Rob Aug 11 '14 at 12:56
  • 4
    looks like the mark as duplicate is the wrong way round as this was asked first on Jul 9'14 – Max MacLeod Jun 14 '16 at 10:50
  • Title aside, this question is specific to a `UICollectionView` and `UITableView`. The marked duplicate is much more general. I recommend this question be reopened. – Suragch Jun 23 '16 at 04:52
  • 2
    As the duplicate question is applicable to this question as well, I suggest to leave this closed. Answers would only replicate the other topic. – Eiko Jun 23 '16 at 07:27
  • 1
    Those voting to re-open this question should consider the fact that it's the #1 result on Google for "*swift fatal error unexpectedly found nil while unwrapping an optional value*" – which I imagine is a query that most new Swift developers will do after abusing the crash operator `!` or implicitly unwrapped optionals for the first time. We should be directing these people to a canonical Q&A on this topic, rather than leaving them on a specific question about `UICollectionView`. If this question is to be re-opened, the title should be changed to reflect the specific problem. – Hamish Jun 27 '16 at 07:53
  • @MaxMacLeod The age of a question is actually fairly irrelevant when it comes to duplicates, it's the content of the questions and answers that really matters. IMO we should be trying to funnel people to a canonical Q&A about this error (seeing as how often people ask about it) rather than to a specific question about `UICollectionView`. – Hamish Jun 27 '16 at 08:01
  • This solved my problem : http://stackoverflow.com/a/25166762/3411787 – Mohammad Zaid Pathan Sep 03 '16 at 21:25

13 Answers13

103

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.

nhgrif
  • 58,130
  • 23
  • 123
  • 163
Connor
  • 60,945
  • 26
  • 140
  • 138
81

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.

Max MacLeod
  • 24,338
  • 10
  • 91
  • 123
25

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."

Community
  • 1
  • 1
Ron Fessler
  • 2,633
  • 1
  • 14
  • 22
22

I don't know is it bug or something but your labels and other UIs does not initialized automatically when you use custom cell. You should try this in your UICollectionViewController class. It worked for me.

override func viewDidLoad() {
    super.viewDidLoad()

    let nib = UINib(nibName: "<WhateverYourNibName>", bundle: nil)
    self.collectionView.registerNib(nib, forCellReuseIdentifier: "title")
}
Bhavin Ramani
  • 3,133
  • 5
  • 29
  • 41
greeninaqua
  • 221
  • 1
  • 5
13

Replace this line cell.labelTitle.text = "This is a title"
with cell.labelTitle?.text = "This is a title"

iOS Developer
  • 417
  • 5
  • 10
6

I got his error when i was trying to access UILabel. I forgot to connect the UILabel to IBOutlet in Storyboard and that was causing the app to crash with this error!!

Nilesh
  • 701
  • 5
  • 14
Pruthvid
  • 683
  • 10
  • 19
3

I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.

I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.

In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.

Melly
  • 655
  • 5
  • 6
2

fatal error: unexpectedly found nil while unwrapping an Optional value

  1. Check the IBOutlet collection , because this error will have chance to unconnected uielement object usage.

:) hopes it will help for some struggled people .

Kishore Kumar
  • 3,639
  • 2
  • 20
  • 45
1

I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.

First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )

I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.

var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).

So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.

Im guesssing your label should always be there?

So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.

Christer
  • 1,613
  • 16
  • 33
  • I was having this issue with a `PFQueryTableViewController`. After reading this answer I had a lightbulb moment that the table in Parse may be empty (even though it's not but maybe for first use it returns nil as default?). But i changed from which column I was querying from and it works. – Lukesivi Dec 23 '15 at 17:11
1

Nil Coalescing Operator can be used as well.

rowName = rowName != nil ?rowName!.stringFromCamelCase():""
Abhijeet
  • 7,483
  • 3
  • 60
  • 70
1

I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.

ekeith
  • 634
  • 1
  • 8
  • 27
0

I was having the same issue and the reason for it was because I was trying to load a UIImage with the wrong name. Double-check .setImage(UIImage(named: "-name-" calls and make sure the name is correct.

Hugo Sequeira
  • 474
  • 4
  • 10
0

Same message here, but with a different cause. I had a UIBarButton that pushed a segue. The segue lacked an identifier.

ICL1901
  • 7,211
  • 13
  • 86
  • 130