Why is my Swift loop failing with error “Can't form range with end < start”?

后端 未结 6 1626
北海茫月
北海茫月 2021-02-05 01:44

I have a for loop that checks if a number is a factor of a number, then checks if that factor is prime, and then it adds it to an array. Depending on the original number, I wil

6条回答
  •  无人及你
    2021-02-05 02:11

    Both ClosedRange and CountableRange throw this error unless start <= end. One problem with using stride(from:to:by) is that it returns a Strideable and not a Range, which doesn't work with the "is in range" operator ~=. To handle these cases, I use an extension which gives me a bounds-safe range, where invalid ranges become an empty range:

    extension Int {
      func until(_ end: Int) -> CountableRange {
        return self <= end ? self.. CountableRange {
        return self <= end ? self..<(end + 1) : self..

    Both return CountableRange so that an invalid through range becomes an empty range. (Side note: the name until is chosen because this "safe" range behaves the same as until ranges in Kotlin/Android).

    Usage:

    for i in 0.until(3) { /* do something */ }
    
    let printRange = { (range: Range) -> Void in
      for i in range {
        print(i, terminator: " ")
      }
      print()
    }
    printRange(0.until(3))  // prints "0 1 2"
    printRange(0.until(0))  // prints ""
    printRange(3.until(0))  // prints ""
    printRange(0.through(3))  // prints "0 1 2 3"
    printRange(0.through(0))  // prints "0"
    printRange(3.through(0))  // prints ""
    print(0.until(1) ~= -1)  // prints "false"
    print(0.until(1) ~= 0)  // prints "true"
    print(0.until(1) ~= 1)  // prints "false"
    print(0.until(0) ~= 0)  // prints "false"
    print(1.until(0) ~= 0)  // prints "false"
    print(0.through(1) ~= -1)  // prints "false"
    print(0.through(1) ~= 0)  // prints "true"
    print(0.through(1) ~= 1)  // prints "true"
    print(0.through(0) ~= 0)  // prints "true"
    print(1.through(0) ~= 0)  // prints "false"
    

提交回复
热议问题