indices
和for value in
很好地给了我寻找的循环但是我需要更进一步,将字典的值分配给字符串的匹配字符然后执行得分计算。
我想知道实现这一目标的最快捷方式。这可以使用map
吗? let curChar = n.map({ print($0) })
。
另一个问题是Javascript允许您轻松使用类型的异构字典,但是使用Swift我们需要匹配类型。
var dict: [String:Any] = ["a":1, "j":1, "s":1, "b":2, "k":2,"r":9/*...*/]
let n = "lighthouse"
var nScore = 0
for i in n.indices[n.startIndex..<n.endIndex] {
let curChar = n[i]
var curVal = dict[curChar]
nScore = nScore + curVal
原始Javascript块。
var dict = {A:1, J:1, S:1, B:2, K:2, T:2...};
var n = "lighthouse";
var nScore = 0;
for( var i = 0; i < n.length; i++ );
{
var curChar = n.charAt( i );
var curVal = dict[ curChar ];
nScore = nScore + curVal;
}
答案 0 :(得分:0)
n[i]
的类型为Character
,因此应该是键类型
字典而不是String
。值类型应为Int
:
let dict: [Character: Int] = ["a": 1, "j": 1, "s": 1, "b": 2, "k": 2, "r": 9 /* ... */]
您还必须定义用作分数的“默认值”
对于在字典中找不到的字符,可以这样做
使用nil-coalescing运算符??
:
let n = "lighthouse"
var nScore = 0
for i in n.indices[n.startIndex..<n.endIndex] {
let curChar = n[i]
let curVal = dict[curChar] ?? 0
nScore = nScore + curVal
}
或者更简单,直接枚举字符串的字符:
for c in n {
let curVal = dict[c] ?? 0
nScore = nScore + curVal
}
使用reduce()
时更短:
let n = "lighthouse"
let nScore = n.reduce(0) { (score, c) in
score + (dict[c] ?? 0)
}
可以使用“速记参数”更紧凑地编写:
let n = "lighthouse"
let nScore = n.reduce(0) { $0 + (dict[$1] ?? 0) }
如果你有完全控制可能的字符 在输入字符串中出现,保证(!)字典 定义所有这些值的值然后您可以强制解包字典查找,例如
let n = "lighthouse"
let nScore = n.reduce(0) { $0 + dict[$1]! }
但如果找不到某个字符,这将在运行时崩溃。
如果你定义一个函数
func numericScore(_ str: String) -> Int {
return str.reduce(0) { $0 + (dict[$1] ?? 0) }
}
然后您可以轻松地将其应用于单个字符串
let nScore = numericScore("lighthouse")
或将其映射到字符串数组
let words = ["lighthouse", "motorcycle"]
let scores = words.map(numericScore)
或计算字符串数组的总分(再次使用reduce
):
let words = ["lighthouse", "motorcycle"]
let totalScore = words.reduce(0) { $0 + numericScore($1) }
// Alternatively in two steps:
let scores = words.map(numericScore)
let totalScores = scores.reduce(0, +)