Quick error "Unable to adjust value of type [Uint8]"

I thought about this for the last hour, and I ran out of hair.

I enjoy AdventOfCode.com. Day 4 (10/10, will play again) and I want this little function to work. (Please do not comment on how incredibly beautiful my code is. It should have been quick and dirty, but now it’s just dirty. Damn, I don’t even know if the code has a chance to work. 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 when theDigest[theCount] is “It is not possible to adjust the value of type“ [UInt8]. ”Although I am not familiar with Swift, I am sure that it tells me that I cannot use an index (of any type) in the UInt8s array. attention, however, that the print(theDigest[0]) line print(theDigest[0]) does not cause errors.

I was looking for the hell out of this, but either I am missing an obvious solution or I can’t interpret the results that I found, most of which seem inappropriate for such a seemingly simple problem.

+5
source share
1 answer

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

 theDigest[theCount] as Int 

You need to create a new Int from UInt8 using

 Int(theDigest[theCount]) 

instead.

If you don’t understand the reason for some error message, it is often useful to break up a complex expression into a few 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.

+18
source

Source: https://habr.com/ru/post/1237530/


All Articles