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

给出C#中的以下枚举和switch / case,例如根据其状态返回文本框的边框颜色.
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来执行此操作,方法是在认情况下移动共享行为,并在您希望发生共享行为的所有情况下使用fallthrough.

例如,如果这是你的枚举(添加了第3个案例,表明它可以处理多个掉落):

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()
}

每次尝试都将执行点移动到下一个案例,直到认情况.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...