交换机语句中的字符串:' String'不符合协议' IntervalType'

时间:2014-11-11 12:38:32

标签: 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'

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

4 个答案:

答案 0 :(得分:57)

在switch语句中使用optional时会显示此错误。 只需解开变量,一切都应该有效。

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

答案 1 :(得分:17)

尝试使用:

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

答案 2 :(得分:13)

我在prepareForSegue()中有同样的错误消息,我认为这是相当常见的。错误信息有点不透明,但这里的答案让我走上正轨。如果有人遇到这种情况,你就不需要任何类型转换,只需对switch语句进行有条件的解包: -

if let segueID = segue.identifier {
    switch segueID {
        case "MySegueIdentifier":
            // prepare for this segue
        default:
            break
    }
}

答案 3 :(得分:5)

而不是不安全的力量展开..我发现测试可选案例更容易:

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

(请参阅添加到案例中)

相关问题