Search code examples
swiftstrideswift2

Using stride() on UInt in Swift 2.2 will not compile


I am trying to use the stride() function on UInt variables, but the code will not compile:

let s = UInt(1)
let by = UInt(2)
let to = UInt(10)

for i: UInt in s.stride(to: to, by: by) {

}

The compile error is:

Cannot invoke 'stride' with an argument list of type '(to: UInt, by: UInt)'

The Swift 2.2 doc, states that it should be possible: http://swiftdoc.org/v2.2/type/UInt/#func-stride-to_by_

Is it a Swift bug or am I doing something wrong?


Solution

  • In https://github.com/apple/swift/blob/master/stdlib/public/core/Stride.swift it is stated that

    The UnsignedIntegerTypes all have a signed Stride type.

    That makes sense because otherwise it would be impossible to iterate from a larger to a smaller number.

    Therefore in your case it should be

    let by = Int(2)
    

    or just

    let by = 2