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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With