user1953977
user1953977

Reputation: 163

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

I am working on a Swift iOS application. I am getting the compile error in for-in loop. 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

Upvotes: 0

Views: 85

Answers (3)

Lachezar
Lachezar

Reputation: 6703

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.

enter image description here

As you can see the type of valueName is (String, String).

Upvotes: 1

Sergii Martynenko Jr
Sergii Martynenko Jr

Reputation: 1407

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.

in your code, you're trying to traverse key:value pairs. I suspect, error arise once compiler reaches case - it is trying to compare String to Tuple, which is not known how to do.

Upvotes: 1

ABakerSmith
ABakerSmith

Reputation: 22939

valueName is a tuple, you therefore need to access one of its elements - either the key or value in this case. 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")
    }
}

Upvotes: 1

Related Questions