简体   繁体   English

Swift错误“无法下标类型[Uint8]的值”

[英]Swift error “Cannot subscript a value of type [Uint8]”

I've been puzzling over this one for about the last hour and am running out of hair. 大约在最后一小时,我一直在为这个问题感到困惑,而且我的头发已经不多了。

I'm having fun with AdventOfCode.com Day 4 (10/10, would play again) and want this little function to work. 我正在玩AdventOfCode.com第4天(10/10,将再次播放),并希望这个小功能工作。 (Please don't comment on just how exceedingly beautiful my code isn't. This was meant to be quick and dirty, but it's now just dirty. Heck, I don't even know if the code stands a chance of working. Anywho...) (请不要评论我的代码是多么美丽。这本来就是快速而又脏的,但它现在只是肮脏的。哎呀,我甚至不知道代码是否有机会工作.Allwho ...)

func countDigestLeadingZeros( theDigest:[UInt8] ) -> Int {
var theCount: Int = 0

print(theDigest[0])

while ((theCount < 16) && (countLeadingZeroNybbles( theDigest[theCount] as Int)>0)) {
        theCount++
}

return theCount
}

The error occurs at the theDigest[theCount] and is "Cannot subscript a value of type '[UInt8]'". 该错误发生在theDigest[theCount]并且是“无法下标类型的值'[UInt8]'”。 Though unfamiliar with Swift, I'm pretty sure what it's telling me is that I can't use an index (of any sort) on an array of UInt8s. 虽然不熟悉Swift,但我很确定它告诉我的是我不能在UInt8s数组上使用索引(任何类型)。 Note, however, that the print(theDigest[0]) line causes no errors. 但请注意, print(theDigest[0])行不会导致错误。

I've Googled the heck out of this one, but either I'm missing the obvious solution or am unable to interpret the results I've found, most of which seem irrelevant to such a seemingly simple problem. 我已经用Google搜索了这个,但要么我错过了明显的解决方案,要么无法解释我发现的结果,其中大部分看起来与这个看似简单的问题无关。

The error message is misleading. 错误消息具有误导性。 The problem is that you cannot convert an UInt8 to Int with 问题是你无法 UInt8 转换Int

theDigest[theCount] as Int

You have to create a new Int from the UInt8 with 你必须从UInt8 创建一个新的Int

Int(theDigest[theCount])

instead. 代替。

If you don't understand the cause for some error message it is often helpful to split a complex expression into several simple ones. 如果您不理解某些错误消息的原因,将复杂表达式拆分为几个简单表达式通常很有帮助。 In this case 在这种情况下

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)

gives a constructive error message for the second line. 为第二行提供了建设性的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM