[swift-users] Looping through all values between UInt8.min and UInt8.max
Nate Cook
natecook at gmail.com
Fri Apr 8 09:43:05 CDT 2016
You can stride through the maximum value of a type if you land right on it:
for i in UInt8.min.stride(through: UInt8.max, by: 1) {
print(i)
}
Nate
> On Apr 8, 2016, at 9:21 AM, Erica Sadun <erica at ericasadun.com> wrote:
>
>
>> On Apr 8, 2016, at 3:48 AM, tuuranton--- via swift-users <swift-users at swift.org> wrote:
>>
>> print(UInt8.min) //0
>>
>> print(UInt8.max) //255
>>
>>
>>
>> //Is there an easy way to loop between all values
>>
>> //between (and including both) UInt8.min and UInt8.max?
>>
>>
>>
>> //This doesn't work.
>>
>> //Runtime crash because UInt8.max has no successor.
>>
>> for i in UInt8.min...UInt8.max {
>>
>> print(i)
>>
>> }
>>
>
> Easy? No.
>
> // Range Index has no valid successor
> for i in UInt8.min ... UInt8.max {
> print(i)
> }
>
> // '...' cannot be applied to two 'UInt8' operands
> for i in UInt8.min ... UInt8.max as ClosedInterval {
> print(i)
> }
>
> // Stops at 254
> for i in UInt8.min ..< UInt8.max {
> print(i)
> }
>
>
> This works, but ugh:
>
> for i : Int in numericCast(UInt8.min)...numericCast(UInt8.max) {
> guard let j: UInt8 = UInt8(i) else { fatalError("Nope") }
> print(j)
> }
>
> cc'ing in a few people to the white courtesy range phone.
>
> -- E
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160408/a1accb3d/attachment.html>
More information about the swift-users
mailing list