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

开关语句中的字符串:’String’不符合协议’IntervalType’

发布时间:2020-12-14 05:57:44 所属栏目:百科 来源:网络整理
导读:我在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
我在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")
}

在“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")
}

编辑:
如果您不想强制展开可选项,可以使用防护。参考:Control Flow: Early Exit

(编辑:李大同)

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

    推荐文章
      热点阅读