Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?

Tags:

swift

I have the following model:

class Word: NSManagedObject {
    @NSManaged var definitions: NSSet
}

Then, in one of my view controllers, I have the following property:

var word: Word?

However, if I try to do this:

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
     return self.word?.definitions.count
}

I get an error:

Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?

According to the documentation, the value of an optional chaining call is also optional, so .count should return an optional Int. So I tried unwrapping it:

return self.word?.definitions.count!

But that still results in the same error. What's the right way to do this?

like image 537
Snowman Avatar asked Jul 22 '14 00:07

Snowman


1 Answers

The problem is the order of operations. The cleanest way to do this would be to stop optional chaining (if you really don't want to handle the nil case).

return self.word!.definitions.count

But I recommend doing this for safety:

if let actualWord = self.word {
   return actualWord.definitions.count
}
else {
   return 0
} 

Or even shorter:

return self.word ? self.word!.definitions.count : 0

Otherwise, you might as well declare word as an implicitly unwrapped optional and not have to worry about it:

var word: Word!

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
    return self.word.definitions.count
}
like image 156
drewag Avatar answered Oct 20 '22 07:10

drewag