Here is how I'm returning the number of rows for a table view:
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let dataCount = self.data?.count {
return dataCount
} else {
return 0
}
}
However, I wanted to use optional chaining to make it more succinct... but the compiler just isn't happy with my code. I try this:
return self.data?.count
and it complains the count is of type Int? and I should force unwrap it, so I do this:
return self.data?.count!
and it complains that count is of type Int. Using optional chaining, it should only get the count if data if not nil, and if the array is not nil then I know that count will return ok.
What am I missing? thanks
It's a matter of the scope:
Alternatively with optional chaining
which evaluates to zero if
self.data
isnil
, whereas the first solution would throw a runtime exception in that case.