Reputation: 1498
I have a dictionary of type Dictionary<String, Int>
and I'm trying to subscript it with a String
. I get the error
Cannot subscript a value of type 'Dictionary<String, Int>' with an index of type 'String'
Here is the whole method. I am running Swift 1.2 (Xcode 6.4), but I have also tried it and the same error occurs in Swift 2.0 (Xcode 7b4).
Here is the whole method:
override func isSatisfied<String, Int>(assignment: Dictionary<String, Int>) -> Bool {
// if all variables have been assigned, check if it adds up correctly
if assignment.count == variables.count {
if let s = assignment["S"], e = assignment["E"], n = assignment["N"], d = assignment["D"], m = assignment["M"], o = assignment["O"], r = assignment["R"], y = assignment["Y"] {
let send: Int = s * Int(1000) + e * Int(100) + n * Int(10) + d
let more: Int = m * Int(1000) + o * Int(100) + r * Int(10) + e
let money: Int = m * 10000 + o * 1000 + n * 100 + e * 10 + y
if (send + more) == money {
return true;
} else {
return false;
}
} else {
return false
}
}
// until we have all of the variables assigned, the assignment is valid
return true
}
The problem line is if let s = assignment["S"]
Also here is the sourcecode repository: https://github.com/davecom/SwiftCSP
And here is the specific file: https://github.com/davecom/SwiftCSP/blob/master/SwiftCSP/SwiftCSPTests/SendMoreMoneyTests.swift
Upvotes: 0
Views: 323
Reputation: 40965
The problem lies here:
func isSatisfied<String, Int>(assignment: Dictionary<String, Int>) -> Bool {
^=== ^===
You have defined this function as generic, with two placeholders called String
and Int
. These will mask the regular types. Delete them, as this probably isn’t what you want.
It’s usually easier, when something strange like this happens, to reduce the case down to just show the problem. I didn’t spot what was wrong until I tried trimming your function down to basically this:
(p.s. [String:Int]
is shorthand for Dictionary<String,Int>
)
Upvotes: 3