Switch 语句中的字符串 : 'String' does not conform to protocol 'IntervalType'

标签 string swift switch-statement

我在 Swift 的 switch 语句中使用字符串时遇到问题。

我有一本名为 opts 的字典声明为 <String, AnyObject>

我有这个代码:

switch opts["type"] {
case "abc":
    println("Type is abc")
case "def":
    println("Type is def")
default:
    println("Type is something else")
}

case "abc" 线上和 case "def"我收到以下错误:

Type 'String' does not conform to protocol 'IntervalType'

有人可以向我解释我做错了什么吗?

最佳答案

当在 switch 语句中使用可选项时会显示此错误。 只需打开变量,一切都应该正常工作。

switch opts["type"]! {
  case "abc":
    println("Type is abc")
  case "def":
    println("Type is def")
  default:
    println("Type is something else")
}

编辑: 如果你不想对可选的进行强制解包,你可以使用 guard。引用:Control Flow: Early Exit

关于Switch 语句中的字符串 : 'String' does not conform to protocol 'IntervalType' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26865132/

相关文章:

c - 指向字符串的动态 char 指针数组

objective-c - 如何使用 NSScanner?

ios - 在标记顶部显示自定义 View

JAva 获取类变量 : Multiple methods or one Method with switch

c# - 全局设置 String.Compare/CompareInfo.Compare 为 Ordinal

java - Android字符串,我应该使用strings.xml还是java字符串

swift - 更改 Firebase 观察器 SWIFT 4 后函数返回

ios - 如何仅在 CGRect 中使用 Apple Vision 检测条形码?

c - 使用 Switch 语句的质数计数器(输出错误)?

javascript - 背景切换器,当 div 到达页面顶部时