简体   繁体   English

由于类型String不符合协议IntervalType而导致Swift for-in循环错误

[英]Swift for-in loop error as type String doesn't conform to protocol IntervalType

I am working on a Swift iOS application. 我正在开发Swift iOS应用程序。 I am getting the compile error in for-in loop. 我在for-in循环中遇到编译错误。 Please check the code below, not sure why is this error throwing here? 请检查以下代码,不确定为什么会在这里引发此错误?

var listDict : Dictionary = ["Insurance":"home", "Saving":"MutualFund"]
for valueName in listDict {

    switch valueName {

        case "Insurance":
            println("My insurance mname")
        default:
            println("Defualt")
    }        
}

and compile error I got is, 我得到的编译错误是

Type String doesn't conform to protocol IntervalType

valueName is a tuple, you therefore need to access one of its elements - either the key or value in this case. valueName是一个元组,因此您需要访问其元素之一-在这种情况下为键或值。 Taking your example: 以您的示例为例:

for valueName in listDict {
    switch valueName.0 {
    case "Insurance":
        print("Value = \(valueName.1)")
    default:
        print("Defualt")
    } 
}

Or, which I personally think is more readable: 或者,我个人认为更具可读性:

for (key, value) in listDict {
    switch key {
        case "Insurance":
            println("Value = \(value)")
        default:
            println("Default")
    }
}

Try this 尝试这个

var listDict : Dictionary = ["Insurance":"home", "Saving":"MutualFund"]
for valueName in listDict.keys {

    switch valueName {

    case "Insurance":
       println("My insurance mname")
    default:
       println("Defualt")
   }

}

Here you will traverse through all keys of your dictionary, which you intend to do according to your case statement. 在这里,您将遍历字典中的所有键,您打算根据case语句进行操作。

in your code, you're trying to traverse key:value pairs. 在您的代码中,您尝试遍历key:value对。 I suspect, error arise once compiler reaches case - it is trying to compare String to Tuple, which is not known how to do. 我怀疑,一旦编译器case ,就会出现错误-它试图将String与Tuple进行比较,这是未知的。

As pointed out already, the structure you should expect is a tuple. 如前所述,您应该期望的结构是一个元组。

You can easily check what is the type of a variable (if not explicitly stated) by clicking on the "Quick help" in your Xcode project. 通过单击Xco​​de项目中的“快速帮助”,可以轻松检查变量的类型(如果未明确说明)。

在此处输入图片说明

As you can see the type of valueName is (String, String) . 如您所见, valueName的类型为(String, String)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM