大约在最后一小时,我一直在为这个问题感到困惑,而且我的头发已经不多了.
我正在玩AdventOfCode.com第4天(10/10,将再次播放),并希望这个小功能工作.(我的代码是不是有多么绝色请不要发表评论,这本来是快速和肮脏的,但它现在只是脏了.哎呀,我甚至不知道如果代码代表工作的机会.Anywho ...)
func countDigestLeadingZeros( theDigest:[UInt8] ) -> Int {
var theCount: Int = 0
print(theDigest[0])
while ((theCount < 16) && (countLeadingZeroNybbles( theDigest[theCount] as Int)>0)) {
theCount++
}
return theCount
}
Run Code Online (Sandbox Code Playgroud)
错误发生在theDigest[theCount]和"是不能下标类型的值'[UInt8]'".虽然不熟悉Swift,但我很确定它告诉我的是我不能在UInt8s数组上使用索引(任何类型).但请注意,该print(theDigest[0])行不会导致错误.
我已经用Google搜索了这个,但要么我错过了明显的解决方案,要么无法解释我发现的结果,其中大部分看起来与这个看似简单的问题无关.
Mar*_*n R 19
错误消息具有误导性.问题是,你不能
转换的UInt8,以Int与
theDigest[theCount] as Int
Run Code Online (Sandbox Code Playgroud)
你必须从with 创建一个新Int的UInt8
Int(theDigest[theCount])
Run Code Online (Sandbox Code Playgroud)
代替.
如果您不理解某些错误消息的原因,将复杂表达式拆分为几个简单表达式通常很有帮助.在这种情况下
let tmp1 = theDigest[theCount]
let tmp2 = tmp1 as Int // error: cannot convert value of type 'UInt8' to type 'Int' in coercion
let tmp3 = countLeadingZeroNybbles(tmp2)
Run Code Online (Sandbox Code Playgroud)
为第二行提供了建设性的错误消息.