2

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

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
bandejapaisa
  • 26,576
  • 13
  • 94
  • 112
  • Have you tried changing the return type to `Int!` instead of `Int` ? – dustincarr Nov 11 '14 at 19:10
  • @dustincarr You can't do that because the method is defined in the UITableViewDatasource protocol, and by changing it's return type, you are changing the method signature - which means you no longer conform to the protocol. – bandejapaisa Nov 12 '14 at 09:46

1 Answers1

7

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Martin is correct. If I were you, I would use his second option, the nil coalescing operator. Forcing an unwrap could give you unwanted behavior at runtime, but the nil coalescing should be your safest bet. – BJ Miller Nov 12 '14 at 00:39