gpt4 book ai didi

swift - 将默认情况与其他情况相结合

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:14 24 4
gpt4 key购买 nike

例如,在 C# 中给出以下枚举和一个开关/大小写以根据其状态返回文本框的边框颜色。

enum TextboxState {
Default,
Error
}

switch(foo) {
default:
case TextboxState.Default: return Color.Black;
case TextboxState.Error: return Color.Red;
}

所以基本上我通过添加 default: case 来定义一个真实的而不只是按照约定的默认状态 aka TextboxState.Default。如果新值被添加到枚举中,我只是想这样做以防止将来发生重大变化。

根据 Swift 书,这是不可能的:

“If it is not appropriate to provide a switch case for every possible value, you can define a default catch-all case to cover any values that are not addressed explicitly. This catch-all case is indicated by the keyword default, and must always appear last.”

该段落对此非常清楚,所以我假设我上面的模式不适用于 Swift 还是我错过了什么?是否有另一种方法来归档类似上述代码的内容?

最佳答案

您可以使用 fallthrough 来做到这一点,方法是在 default 情况下移动共享行为,并在所有情况下使用 fallthrough您希望共享行为发生。

例如,如果这是您的枚举(添加了第三个案例以表明它可以处理多个失败):

enum TextboxState {
case Default
case Error
case SomethingElse
}

您可以将 switch 语句格式化如下:

switch(foo) {
case TextboxState.Error:
return UIColor.redColor()

case TextboxState.Default:
fallthrough

case TextboxState.SomethingElse:
fallthrough

default:
return UIColor.blackColor()
}

每个 fallthrough 都会将执行点移动到下一个案例,直到 default 案例。

关于swift - 将默认情况与其他情况相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26125299/

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