gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:55:37 28 4
gpt4 key购买 nike

我有一个计算新分数的方法。下面的方法有效,但问题是代码本身看起来可以被显着清理。我只是不知道什么是最好的方法。我根据 filterString 和枚举 individualScoreState

分配 scoreCount 一个整数
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 是一个结构的实例。

最佳答案

你可以这样做:

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
}

@ 如果@"ScoreB"在 Objective-C 中使用但在 Swift 中不用于字符串文字,只需将其删除。

关于Swift:在另一个 switch 语句中重构 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53904946/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com