如何为一个枚举提供一个可选的Tableview部分用例

问题描述 投票:0回答:1

我有3个部分显示可选变量是否不为nil,只有2个。我想要的是将所有这些都包含在一个枚举(或struct中,如果不可能的话)。

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")
            }
        }
ios swift generics
1个回答
0
投票

我想不出如何用枚举或结构来缩短您的代码,但是这是我将如何用一组闭包来缩短它。

var sectionClosures = [
    { qrCodeCell(tableView, indexPath) }
    { trainingMethodCell(tableView, indexPath) }
]
if let currentTraining = self.currentTraining {
    sectionClosures.insert(
        { currentTrainingCell(tableView, indexPath, currentTraining: currentTraining) }, 
        at: 0)
}
if (0..<sectionClosures.count).contains(indexPath.section) {
    sectionClosures[indexPath.section]()
} else {
    fatalError("No more sections allowed")
}
© www.soinside.com 2019 - 2024. All rights reserved.