我有一个Dictionary<String, Int>
类型的字典,我试图用String
下标它。我收到了错误
Cannot subscript a value of type 'Dictionary<String, Int>' with an index of type 'String'
这是整个方法。我正在运行Swift 1.2(Xcode 6.4),但我也试过了,并且在Swift 2.0(Xcode 7b4)中也出现了同样的错误。
以下是整个方法:
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
}
问题在于,如果让s =赋值[&#34; S&#34;]
此处还有源代码存储库: https://github.com/davecom/SwiftCSP
这是特定文件: https://github.com/davecom/SwiftCSP/blob/master/SwiftCSP/SwiftCSPTests/SendMoreMoneyTests.swift
答案 0 :(得分:3)
问题在于:
$new_phone1 = "1231231234";
$new_phone2 = "1234567892";
$new_phone3 = "1234343432";
您已将此功能定义为通用,其中两个占位符名为func isSatisfied<String, Int>(assignment: Dictionary<String, Int>) -> Bool {
^=== ^===
和String
。这些将掩盖常规类型。删除它们,因为这可能不是你想要的。
当发生类似这样的奇怪事件时,通常会更容易将案例减少到只显示问题。直到我尝试将你的功能调整到基本上这个时,我才发现出了什么问题:
(p。Int
是[String:Int]
)