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

后端 未结 6 1642
北海茫月
北海茫月 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:08

    Swift 5

    If you need a loop with dynamic value-range, I suggest that using stride(to:by:) instead of ..< or ...

    Basically ..< or ... will be crashed if start_index > end_index.

    This will be crash:

    let k = 5
    for i in 10...k { print("i=\(i)") }
    for i in 10..

    How to fix:

    let k = 5
    for i in stride(from: 10, through: k, by: 1) { print("i=\(i)") }
    for i in stride(from: 10, to: k, by: 1) { print("i=\(i)") }
    

    NOTE:

    The code above won't print out anything, but it won't be crash when execution.

    Also, if you want to stride from a higher number to a lower number then the by parameter needs to be changed to a negative number.

    Reference:

    • http://michael-brown.net/2016/using-stride-to-convert-c-style-for-loops-to-swift-2.2/
    • http://swiftdoc.org/v2.1/protocol/Strideable/

提交回复
热议问题