Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionReusableView - Missing return in a function

I had a weird problem running into considering a header of a UICollectionView.

I basically used the code from: http://www.raywenderlich.com/78551/beginning-ios-collection-views-swift-part-2

func collectionView(collectionView: UICollectionView,
        viewForSupplementaryElementOfKind kind: String,
        atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd.MM.yyyy' - 'HH:mm'"
            //1
            switch kind {
                //2
            case UICollectionElementKindSectionHeader:
                //3
                let h =
                collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "eventHeaderView", forIndexPath: indexPath) as eventHeader


                h.eventFirstline.text = "First Line"
                h.eventSecondline.text = thisEvent.eventName

                h.eventDate.text = dateFormatter.stringFromDate(thisEvent.startDate)

                h.eventDescription.text = thisEvent.shortDescription

                return h
            default:
                //4
                assert(false, "Unexpected element kind")
            }
    }

All that works perfectly fine when instantly deploying to either the simulator or a real device, but oddly when I wanna build an Ad-Hoc Package for testing purposes it tells me

Missing return in a function expected to return 'UICollectionReusableView'

Ok so far so good, there is nothing outside the switch-case so it could return nothing - but why does it not give any warnings on "hot deploy" only when I try to build a package?

like image 904
longbow Avatar asked Mar 19 '15 15:03

longbow


1 Answers

assert() is evaluated only in the Debug configuration. When you build an archive then the code is compiled in the Release configuration (with optimizations) and the condition is simply ignored (assumed to be true). Therefore the compiler complains about the missing return value.

You can use

fatalError("Unexpected element kind")

instead. fatalError() is always evaluated and in addition marked with @noreturn (resp. return type Never in Swift 3) so that the compiler knows that it does not return to its caller.

See also Swift - fatalError with Switch Statements.

like image 108
Martin R Avatar answered Sep 24 '22 02:09

Martin R