-2

I have following code:

class User {

    var listsDict : [String : List]!

    func addList (list : List) -> Void {
        print(list.name)
        listsDict[list.name] = list
    }

    func listForName (name: String) -> List? {
        return listsDict[name]
    }

}


class List {

    let name : String
    var movies : Set<String>

    init(name: String){
        self.name = name
        movies = Set<String>()
    }

    func printList (){
        print(movies)
    }

}

var list = List(name: "List")
list.movies = Set<String>(["LOTR", "SAW", "POC"])
list.printList()


var johny = User()
johny.addList(list: list)

When i call johny.addList(list: list) i got an error:

unexpectedly found nil while unwrapping an Optional value

But there is a value. I created instance of list previously and even print in log name of list (and it successfully printed). Why i got an error?

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

4 Answers4

2

The error occurs because listsDict is declared as implicit unwrapped optional but not initialized.

Instead of using an implicit unwrapped optional property initialize the dictionary non-optional

var listsDict = [String : List]()
vadian
  • 274,689
  • 30
  • 353
  • 361
2

Whenever I found this try of error. I just do this below steps

Just print("variable name") .

then I use

if <variable name> != nil {

}else{

}

This is my way of handling these type of errors.

sabari vasagan
  • 404
  • 5
  • 18
  • 3
    You should use conditional binding instead (`if let ...`, `guard let ...`). It's rare to need to check if a variable is `nil`, without then needing to use the variable – Alexander Jul 24 '17 at 06:14
1

You don't ever assign a value to User.listsDict, thus it's nil when you try to add a value to it. Just part of the reason ! should never be used unless you absolutely have to. And in this case, you don't.

var listsDict : [String : List]!

Should be

var listsDict = [String : List]()
David Berry
  • 40,941
  • 12
  • 84
  • 95
1

You are getting an error because of listsDict[list.name] = list in the method:

func addList (list : List) -> Void {
        print(list.name)
        listsDict[list.name] = list
}

You declared it as:

var listsDict : [String : List]!

Appending to a dictionary without initialize it should cause this error, You should initialize it first (var listsDict = [String : List]()) and I would suggest to declare it as lazy variable:

lazy var listsDict = [String : List]()

and your code should works fine.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143