我有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")
}
}
我想不出如何用枚举或结构来缩短您的代码,但是这是我将如何用一组闭包来缩短它。
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")
}