0

I have a UICollectionViewController that conforms to UICollectionViewDataSource also by defining the following method:

override func collectionView(collectionView: UICollectionView,
                             cellForItemAtIndexPath indexPath: NSIndexPath) 
                             -> UICollectionViewCell {
     // ...
}

Inside that method there is an assertion that fails if execution reaches the default branch of a switch statement. Since this is in the context of a method, an arbitrary return value is needed: nil is my preferred choice.

switch ... {
// ...
default:
    assertionFailure(); return nil
}

This would work in Objective-C but raises a compile-time error in Swift, because the contract defines a non-optional return type.

Nil is incompatible with return type 'UICollectionViewCell'

What is a best practice for handling this situation? I don't want to register/dequeue a special cell type just to satisfy the compiler. Can I somehow get by without returning any value from the default branch, or can I throw an appropriate exception instead (and if so, how)?

Drux
  • 11,992
  • 13
  • 66
  • 116
  • If you're switching on an enum I believe the compiler is smart enough to qualify each case without a default. Otherwise you can return just a default UICollectionViewCell() since it will probably never been executed anyway. – Fred Faust Nov 24 '15 at 21:42
  • @thefredelement I am not switching on an enum but on a near equivalent of `indexPath.section % 2`. – Drux Nov 24 '15 at 21:42
  • 1
    I do almost exactly that with a tableView in an app and return a UITableViewCell() – Fred Faust Nov 24 '15 at 21:44
  • @thefredelement Perfect. (I did not notice the default constructor). If you want to turn your last comment into an answer, I shall accept it. – Drux Nov 24 '15 at 21:45
  • 1
    @Drux, the only way to handle your case is to return a UITableViewCell() as thefredelement said. – nsinvocation Nov 24 '15 at 21:45
  • 1
    If you call `fatalError()` instead of `assertionFailure()` then you don't have to return a dummy cell. – Martin R Nov 24 '15 at 22:08
  • @MartinR Yes, `fatalError()` (and `@noreturn`) appear even better. – Drux Nov 24 '15 at 22:08
  • Nice @MartinR I think that's way better. – Fred Faust Nov 24 '15 at 23:56

0 Answers0