Wednesday, 25 December 2019

How to have one enum with an optional case for tableview section

I have 3 sections to show if an optional variable is not nil and only 2 if it is. What i want is to have all this in an enum(or struct if that is not possible).

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let currentTraining = self.currentTraining {
        switch indexPath.section {
        case 0:
            return currentTrainingCell(tableView, indexPath, currentTraining: currentTraining)
        case 1:
            return qrCodeCell(tableView, indexPath)
        case 2:
            return trainingMethodCell(tableView, indexPath)
        default:
            fatalError("No more sections allowed")
        }
    } else {
        switch indexPath.section {
        case 0:
            return qrCodeCell(tableView, indexPath)
        case 1:
            return trainingMethodCell(tableView, indexPath)
        default:
            fatalError("No more sections allowed")
        }
    }
}

I had something in mind to wrap all this in enums(or structs if that makes more sense) and just switch the cases and shorten my code in cellForRow

enum TrainingSection {
    case qrCode
    case trainingMethod
    // if its nil to make nothing if yes do call the method
    case currentTraining(FTCurrentTraining)
}


from How to have one enum with an optional case for tableview section

No comments:

Post a Comment