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

swift – 将默认情况与其他情况相结合,第1张

概述给出C#中的以下枚举和switch / case,例如根据其状态返回文本框的边框颜色. enum TextboxState { Default, Error}switch(foo) { default: case TextboxState.Default: return Color.Black; case TextboxState.Error: return Color.R 给出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:    fallthroughcase TextBoxState.somethingElse:    fallthroughdefault:     return UIcolor.blackcolor()}

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

总结

以上是内存溢出为你收集整理的swift – 将默认情况与其他情况相结合全部内容,希望文章能够帮你解决swift – 将默认情况与其他情况相结合所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1032198.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存