1
votes

I'm working on a Udemy course for iOS 8 - Swift language. And I keep getting this error when trying to make a To Do List App:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Here is the code:

Here is the code below:

class SecondViewController: UIViewController {

    var toDoItems:[String] = []
    
    @IBOutlet var toDoItem: UITextField!
    
    @IBAction func addItem(sender: AnyObject) {
    
        toDoItems.append(toDoItem.text)
        
        println(toDoItems)
        
    }
    

Any help?

Thanks!!

2
Where did you get that error and what is toDoItem ?Midhun MP

2 Answers

2
votes

I'll assume the error is related to the toDoItem property.

Maybe you forgot to correctly connect that property to the element in the UI, so that variable is null.

You're declaring it as:

@IBOutlet var toDoItem: UITextField!

which means it is an optional value, it might be nil. In this case since you're using ! instead of ?, it means that the variable is implicitly unwrapped when you access it, so you don't have to use it like

toDoItem!.text

The issue is that since that variable is an optional, you must always make sure first that it contains a value before accessing it, so the right code would be:

@IBAction func addItem(sender: AnyObject) {
    if(toDoItem != nil){
        toDoItems.append(toDoItem.text)
    }

    println(toDoItems)

}
0
votes

It is because of the following line:

toDoItems.append(toDoItem.text)

Your IBOutlet is optional, so it's value can be nil. If you forget to connect that to the storyboard, it'll be nil. So in this case it'll cause a crash because you are trying to access a property of nil!!! Change that to:

if let textValue = toDoItem?.text
{
   toDoItems.append(textValue)
}