[swift-evolution] For-loop revisited

Stephen Celis stephen.celis at gmail.com
Thu Feb 25 22:10:46 CST 2016


> OK, let's clean it up a little: use a single floating point type here (Double):
> 
> let w = 20.0
> let h = 5.0
> 
> for var x in (-60.0).stride(to: 60.0, by:  w * 1.2)
> {
>    for var y in (30.0).stride(to: -60.0, by:  -h * 1.2)
>    {
>        print("x = \(x)    y = \(y)")
>    }
> }

For what it's worth, you can keep the Floats and things can still be simple:

    let w: Float = 20
    let h: Float = 5
    for x in Float(-60).stride(to: 60, by: w * 1.2) {
        for y in Float(30).stride(to: -60, by: -h * 1.2) {
            print("x = \(x) y = \(y)")
        }
    }

Inference makes it possible to use integer literals and avoid explicit casts most places.

(To be honest, I'm not sure why the `Float(-60)` and `Float(30)` are required. I would assume that the presence of `w` and `-h` as `by:` arguments would allow the other arguments to be inferred.)

Stephen


More information about the swift-evolution mailing list