gpt4 book ai didi

swift - 加入 bool 优化Swift

转载 作者:行者123 更新时间:2023-11-30 10:01:43 25 4
gpt4 key购买 nike

有没有更好的方法来编写这个 if 语句,它最终在三个变量中产生四个结果?

我研究了守卫和开关,但我不确定其中任何一个是否能很好地捕获连接的 bool 状态?我可以将四个结果单独列出为连接的 bool 语句(例如,isPartialResult == true && returned == nil,等等..),但这不一定更具可读性或效率(需要输入更多内容)。谢谢!

case .BinaryOperation(let function):
if isPartialResult == true {
if calculated == nil {
log += (" \(accumulator) \(symbol)") // add new op
} else {
log += (" \(symbol)") // add symbol to calculated, prepare for new op
calculated = nil
}
} else {
if log.characters.count <= 1 {
log += (" \(accumulator) \(symbol)") // start from beginning
} else {
log += (" \(symbol)") // restart from equal
}
}
executePendingBinaryOperation()
pending = pendingBinaryOperationInfo(binaryFunction: function, firstOperand: accumulator)
isPartialResult = true

最佳答案

给定 3 个值

let isPartialResult = true
let calculated: String?
let log = "hello"

您可以通过这种方式使用开关

switch (isPartialResult, calculated, log.characters.count) {
case (true, nil, _): break
case (true, let _, _): break
case (false, _, 0...1): break
case (false, _, 2...Int.max): break
default: fatalError()
}

现在只需用您的结果替换 4 个休息时间即可。

关于swift - 加入 bool 优化Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163370/

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