Optional Chaining returning an Int

169 views Asked by At

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

1

There are 1 answers

1
Martin R On BEST ANSWER

It's a matter of the scope:

return (self.data?.count)!

Alternatively with optional chaining

return self.data?.count ?? 0

which evaluates to zero if self.data is nil, whereas the first solution would throw a runtime exception in that case.