Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift error "Cannot subscript a value of type [Uint8]"

Tags:

arrays

swift

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. (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...)

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]'". 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. Note, however, that the print(theDigest[0]) line causes no errors.

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.

like image 832
BillEccles Avatar asked Dec 06 '15 22:12

BillEccles


1 Answers

The error message is misleading. The problem is that you cannot convert an UInt8 to Int with

theDigest[theCount] as Int

You have to create a new Int from the UInt8 with

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.

like image 168
Martin R Avatar answered Oct 15 '22 00:10

Martin R