Swift:在另一个switch语句中重构switch语句

时间:2018-12-23 15:43:13

标签: swift struct enums switch-statement refactoring

我有一种计算新分数的方法。下面的方法有效,但是问题在于代码本身看起来可以被大量清理。我只是没有最好的方法。我根据过滤器字符串和枚举scoreCount分配了一个individualScoreState整数

func calculateScore(count: Int, filterString: String, individualScoreState: IndividualScores) -> Int {
    var scoreCount: Int = 0
    var results = Results()

    switch filterString {
    case "ScoreA":
        switch individualScoreState {
        case .firstScore:
            scoreCount = results.firstScoreACount
        case .secondScore:
            scoreCount = results.secondScoreACount
        default:
            scoreCount = results.scoreACount
        }
    case @"ScoreB":
        switch individualScoreState {
        case .firstScore:
            scoreCount = results.firstScoreBCount
        case .secondScore:
            scoreCount = results.secondScoreBCount
        default:
            scoreCount = results.scoreBCount
        }
    default:
        switch individualScoreState {
        case .firstScore:
            scoreCount = results.firstScoreACount + results.firstScoreBCount
        case .secondScore:
            scoreCount =  results.secondScoreACount + results.secondScoreBCount
        default:
            scoreCount = results.scoreACount + results.scoreBCount
        }
    }

   return count / scoreCount
}

//结果结构

struct Results {
    var scoreACount = 0
    var scoreBCount = 0

    var firstScoreACount = 0
    var firstScoreBCount = 0

    var secondScoreACount = 0
    var secondScoreBCount = 0 
}

可能有一种更清洁的方式来处理此问题。也许是将两个开关盒结合起来的一种方法?

编辑:忘记提及此results是结构的实例。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

let notB = filterString != "ScoreB" ? 1 : 0
let notA = filterString != "ScoreA" ? 1 : 0

switch individualScoreState {
case .firstScore:
    scoreCount = notB * results.firstScoreACount + notA * results.firstScoreBCount
case .secondScore:
    scoreCount = notB * results.secondScoreACount + notA * results.secondScoreBCount
default:
    scoreCount = notB * results.scoreACount + notA * results.scoreBCount
}

如果在Objective-C中使用@ {ScoreB“而不是在Swift for String文字中使用@,只需将其删除。