var randomData = Data([UInt8.random(in: 0..<256)])
The compiler flags this as an error because 256 won't fit in a Uint8. Which is correct. But the range is 0..<256 so I should never get back 256.
Right?
var randomData = Data([UInt8.random(in: 0..<256)])
The compiler flags this as an error because 256 won't fit in a Uint8. Which is correct. But the range is 0..<256 so I should never get back 256.
Right?
The issue is that the range type it accepts is Range<UInt8>
so in order to make the bounds you need to have a pair of UInt8
of which 256
is not a valid UInt8
in the first place. This is just UInt8.random(in: 0 ... .max)
D'oh! I didn't realize the complaint was about the argument going into the range itself! Thank you so much.
Same here:
for i: Int8 in 0 ..< 128 {} // 🛑 Integer literal '128' overflows when stored into 'Int8'
for this loop to exit i
should become equal to 128 at some point, but it can't.
A related issue, which has come up on these forums occasionally, is that this code:
for i: UInt8 in 0... {
print(i)
}
Will print 0 through 254, then crash without ever printing 255.
Huh, indeed. Which makes this seemingly equivalent loop different:
var i: UInt8 = 0
while true {
print(i)
i += 1
}
(it does print 255 before trapping).
@Nevin , @tera: Thank you for the interesting examples.
They crash with different error messages though. @Nevin's example seems to dive deeper.
// Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I wonder what the above error message would be on an Apple silicon machine.
// Thread 1: Swift runtime failure: arithmetic overflow