Will Taylor
Will Taylor

Reputation: 551

Unexpectedly found nil while unwrapping an optional yet the variable has a value

I am making a simple to-do list app. I have created a custom tableviewcell with a label and a textview in it. The label is for the title and the textview is for the description. When I try to run the app, it crashes and gives me the following error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

The error is thrown on the line:

cell.taskTitle.text = task.title

but the print statement on the line above prints out "Optional("Task 1")". Why is this?

Here is the whole function:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath)
        as! TaskTableViewCell

    let task = taskList[indexPath.row]
    print(task.title)
    cell.taskTitle.text = task.title
    cell.taskDescription.text = task.description

    return cell
}

Thanks!

EDIT: My taskList is declared globally as:

var taskList: [Task] = [
    Task(title: "Task 1", desc: "Task 1 desc"),
    Task(title: "Task 2", desc: "Task 2 desc"),
    Task(title: "Task 3", desc: "Task 3 desc")
]

My Task class:

class Task {
var title: String?
var description: String?

init(title: String, desc: String) {
    self.title = title
    self.description = desc
}

}

Upvotes: 2

Views: 864

Answers (2)

matt
matt

Reputation: 534950

It's because you're looking in the wrong place. What's nil is not task.title. It is cell.taskTitle.

Of course, now you probably want to know why that is. It's because you are configuring your cell dequeuing mechanism incorrectly. You didn't show how you are doing that, so we have to guess. A common mistake here is to call

tableView.register(TaskTableViewCell.self...

That will actually prevent your cell from being loaded from the storyboard or xib file, and so all your cell's outlets are nil. If you have a line like that in your code, then:

  • If the cell is designed in the storyboard, delete that line.

  • If your cell is designed in a xib file, then replace that line with:

    tableView.register(UINib(nibName:"TaskTableViewCell", bundle:nil)...
    

Upvotes: 3

Y.Awad
Y.Awad

Reputation: 21

First of all it would be better if you used some commands like "po" to display the value of each variable to see whether it was created or not secondly I had this problem before the I used willdispaly function which is a property of the table view and it has a great strength it tells hey you the table view cell finished its load and will about to be display is there anything left you want to change in it before displaying it in this way you are sure that everything was built fine and no nils

Upvotes: 1

Related Questions