[swift-evolution] For loop

Ted F.A. van Gaalen tedvgiosdev at gmail.com
Mon Mar 7 18:48:57 CST 2016


Apart from the indirect .stride method, (which is good for collections)
there are still no adequate equivalents for   
          for;;  
 as used often in ‘traditional’ programming
for floating point numbers. 

Of course, one can also code this in a “while {}”
but this would be cumbersome.

Because of this I am currently replacing for;;
by a global function ‘iterate’ :

/// Tested in Xcode Version 7.2.1 (7C1002) - Playground
// perhaps it should have generic parameters..
// and also a variant with floating point tolerance

func iterate(from from: Double,
                    to: Double,
                    by: Double,
                 block: (v: Double) -> Void)
{
    let low:  Double
    let high: Double
    let moveForward: Bool

    var current = from
    
    if from < to
    {
        low  = from
        high = to
        moveForward = true
    }
    else
    {
        low  = to
        high = from
        moveForward = false
    }
    
    var iterator = 0

    while current >= low  &&
          current <= high
    {
        block(v: current)  // <<<<<<<<<<<<<<<<<<
        
        iterator += 1        // imho  iterator++   looks a lot cleaner 
        if moveForward
        {
            current = low + Double(iterator) * by
        }
        else
        {
            current = high - Double(iterator) * by
        }
    }
}

////// Usage of the above function e.g.: /////////////

var factor = 5.0

iterate(from: 0.0, to: -2.0, by: 0.01,  block:
 {
        (v: Double) in
        print("v = \(v) v * factor \(v * factor)")
 }
)

///////////////////////////////////////////////////////////////////////

This tiny simple function is very efficient.
I did not yet run benchmarks on it,
but it probably is a lot faster than fetching values
from a pseudo-collection as with .stride.

Still, imho a better option would be as a Swift
language element:

for v from v1 to v2 by vstep {}

I will then write a proposal for it, unless
someone has a better solution?


All this would not have been necessary if the
for ;;   was not killed.

Kind Regards
TedvG


 













More information about the swift-evolution mailing list