[swift-users] Looping through all values between UInt8.min and UInt8.max

Daniel Strobusch ds at webwege.de
Fri Apr 8 15:55:50 CDT 2016


I think excluding the upper bound (..<) does not address the problem correctly. The problem occurs on including the upper bound. 

Consider the following simple program 

#!/usr/bin/env swift

if let n: UInt8 = UInt8(Process.arguments[1])
{
    for i in 0...n
    {
        print (i)
    }
}

this program compiles and may even pass some testing. It will run correctly for all values except 255, for which it crashes. The problem is that no one knows how many of these cases we do have in current production code and tracking these issues down may be almost impossible. 
I would say, the take home message for know is, don’t use 0…n (i.e. include the upper bound) unless you are sure that the upper bound cannot be equal to the max value of the type. 

I have not checked out the Swift3 branch which should fix this. Currently, with Swift2.2 I think this is a serious issue. 

Daniel

> On 08.04.2016, at 19:47, Cody Weaver <codyleeweaver at gmail.com> wrote:
> 
> I think an easy answer if I understand the question right is.
> 
> let a: UInt8 = UInt8.min
> let b = UInt8 = UInt8.max
> 
> for c in a..<b {
>    print(c)
> }
> 
> On Fri, Apr 8, 2016 at 10:27 AM Daniel Strobusch via swift-users <swift-users at swift.org> wrote:
> Hi,
> just as a side note, I filed a bug on this some time ago:
> 
> https://bugs.swift.org/browse/SR-1091
> 
> so let’s hope, this gets fixed in Swift3. Its really annoying and dangerous because the error is not recovered at compile time.
> 
> Daniel
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160408/f291977d/attachment.html>


More information about the swift-users mailing list