7 dictionary for-loop input swift
在这下面你可以看到我的代码。我评论了导致错误的行。错误消息:“调用下标时没有完全匹配”。你知道我怎样才能避免这个错误吗?感谢您的帮助!
let dic = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26]
var newwrd = ""
for var i in str ?? "" {
let ci = dic[i] // This line causes the error
}
Run Code Online (Sandbox Code Playgroud)
实际上你应该得到错误
无法使用类型为“String.Element”(也称为“字符”)的参数为类型为“[String : Int]”的值添加下标
str显然String?,枚举字符串时的元素类型是Character,但订阅类型必须是String。
let dic = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26]
for i in str ?? "" { // no need for var i
let ci = dic[String(i)] ?? 0
print(ci)
}
Run Code Online (Sandbox Code Playgroud)
如果字符串包含字典中没有的字符,则结果为 0。
有一种更短的方法,无需辅助字典
for i in str ?? "" where ("a"..."z") ~= i {
let ci = Int(i.asciiValue!) - 96
print(ci)
}
Run Code Online (Sandbox Code Playgroud)