Home > front end >  numberOfRowsInSection if inside Switch
numberOfRowsInSection if inside Switch

Time:10-01

I have this numberOfRowsInSection.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch Section(rawValue: section)! {
        case .slider: return parentVC.selectedCommunity == nil ? 1 : 0
        case .header: return 1
        case .item:
            if case item = PostType.survey.rawValue {
                let sectionItems = parentVC.surveys
                var numberOfRows: Int = sectionItems.count
                for rowItems in sectionItems {
                    numberOfRows  = rowItems.surveyAnswers!.count
                }
                return numberOfRows
            } else { return cellTypes.count }
        }
    }

I want to check if .item is PostType.survey I have tried to show the logic with not working code. if case item = PostType.survey.rawValue { this statement does not work to catch

How can I detect it?

enum Section: Int {
        case slider
        case header
        case item

        static var numberOfSections: Int { return Section.item.rawValue   1 }
        
        var reuseIdentifier: String {
            switch self {
            case .slider: return NewsFeedSliderTableViewCell.reuseIdentifier
            case .header: return NewsFeedPostHeaderTableViewCell.reuseIdentifier
            case .item: return NewsfeedTableViewCell.reuseIdentifier
            }
        }
    }
     

enum PostType: Int {
    case post = 0
    case question = 1
    case survey = 2
}

CodePudding user response:

You are using if case item = PostType.survey.rawValue but item is a enum case inside of Section.

From looking you code, I assume you want to check if section == item.rawValue then after that you check Section.item.rawValue == PostType.survey.rawValue or not.

But as an enum case, Section.item.rawValue = 2 and PostType.survey.rawValue = 2 is always = 2 unless you define differently. So if you compare with section which is Int in your code. The else in your condition in .item which is return cellTypes.count will never be executed.

So instead using if case item = PostType.survey.rawValue {

You can change to if case section = PostType.survey.rawValue { because the thing you need to compare here is rawValue which is an Int or completely remove the condition because both rawValue of item and survey are the same.

  • Related