我有一个这样设置的枚举:
enum Calculators {
case RECTANGLE
case CIRCLE
case TRIANGLE
case TRAPEZOID
case CUBE
case CONE
case SPHERE
case CYLINDER
case ASPHALT
case TACK_SEAL_COAT
case ASPHALT_YIELD
case SIDEWALK
case CONCRETE_DECK_SEALER
case CHIP_SEAL
case AGGREGATE_STOCK_PILE
case BACKFILL
case SALT_STOCK_PILE
case SALT_SPREADER_CALIBRATION
case ROAD_SALT_APPLICATION
static let groups = [[RECTANGLE, CIRCLE, TRIANGLE, TRAPEZOID],
[CUBE, CONE, SPHERE, CYLINDER],
[ASPHALT, TACK_SEAL_COAT, ASPHALT_YIELD, SIDEWALK, CONCRETE_DECK_SEALER, CHIP_SEAL, AGGREGATE_STOCK_PILE, BACKFILL],
[SALT_STOCK_PILE, SALT_SPREADER_CALIBRATION, ROAD_SALT_APPLICATION]]
func getCalculator(category: Int, row: Int) -> Calculators {
if let calculator = Calculators.groups[category][row] {
return calculator
} else {
return Calculators.UNDEFINED
}
}
}
我的想法是,我将传递我想要的计算器类别,然后是特定的计算器,它将返回正确的枚举,所有这些都基于TableView中选择的行。
问题在于我遇到了一个令人困惑的错误。第一个错误发生在if let calculator
行。错误显示为Enum case 'Some' not found in type 'Calculators'
。我不确定为什么要这样做。
这个错误意味着什么,我该如何解决它?
答案 0 :(得分:1)
您的if let
未评估可选项(必需)。数组下标如果超出范围则会崩溃。我想你的意思是:
func getCalculator(category: Int, row: Int) -> Calculators? {
let groups = Calculators.groups
guard groups.indices.contains(category) else { return nil }
let calculatorCateogry = groups[category]
guard calculatorCateogry.indices.contains(row) else { return nil }
return calculatorCateogry[row]
}
答案 1 :(得分:1)
很少有事情 1.添加UNDEFINED作为其中一个案例 2.你也可以将getCalculator声明为静态方法来访问它,如Calculators.getCalculator
为了防止程序在索引超出范围时崩溃,我添加了将返回UNDEFINED的检查。
enum Calculators {
case RECTANGLE
case CIRCLE
case TRIANGLE
case TRAPEZOID
case CUBE
case CONE
case SPHERE
case CYLINDER
case ASPHALT
case TACK_SEAL_COAT
case ASPHALT_YIELD
case SIDEWALK
case CONCRETE_DECK_SEALER
case CHIP_SEAL
case AGGREGATE_STOCK_PILE
case BACKFILL
case SALT_STOCK_PILE
case SALT_SPREADER_CALIBRATION
case ROAD_SALT_APPLICATION
case UNDEFINED
static let groups = [[RECTANGLE, CIRCLE, TRIANGLE, TRAPEZOID],
[CUBE, CONE, SPHERE, CYLINDER],
[ASPHALT, TACK_SEAL_COAT, ASPHALT_YIELD, SIDEWALK, CONCRETE_DECK_SEALER, CHIP_SEAL, AGGREGATE_STOCK_PILE, BACKFILL],
[SALT_STOCK_PILE, SALT_SPREADER_CALIBRATION, ROAD_SALT_APPLICATION]]
func getCalculator(category: Int, row: Int) -> Calculators {
if Calculators.groups.indices.contains(category) {
let calculators = Calculators.groups[category]
if calculators.indices.contains(row) {
return calculators[row]
}
}
return Calculators.UNDEFINED
}
}
let testCalculator = Calculators.RECTANGLE
testCalculator.getCalculator(category: 7, row: 1) // Result: UNDEFINED
testCalculator.getCalculator(category: 1, row: 1) // Result: CONE