加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:26:34 所属栏目:百科 来源:网络整理
导读:给出C#中的以下枚举和switch / case,例如根据其状态返回文本框的边框颜色. enum TextboxState { Default,Error}switch(foo) { default: case TextboxState.Default: return Color.Black; case TextboxState.Error: return Color.Red;} 所以基本上我通过添加d
给出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()
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读