UICollectionReusableView - Missing return in a function

纵饮孤独 提交于 2020-01-10 18:14:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/29149040/uicollectionreusableview-missing-return-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!