gpt4 book ai didi

swift - 调用下标 [Swift] 时没有完全匹配

转载 作者:行者123 更新时间:2023-12-04 17:21:39 26 4
gpt4 key购买 nike

在这下面你可以看到我的代码。我评论了导致错误的行。错误消息:“调用下标时没有完全匹配”。你知道我怎样才能避免这个错误吗?谢谢您的帮助!

        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
}

最佳答案

其实你应该得到错误

Cannot subscript a value of type '[String : Int]' with an argument of type 'String.Element' (aka 'Character')

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)
}
如果字符串包含不在字典中的字符,则结果为 0。

没有辅助字典有更短的方法
for i in str ?? "" where ("a"..."z") ~= i {
let ci = Int(i.asciiValue!) - 96
print(ci)
}

关于swift - 调用下标 [Swift] 时没有完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65794651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com