Reputation: 163
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
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.
As you can see the type of valueName
is (String, String)
.
Upvotes: 1
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
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