1
\$\begingroup\$

I've reached a point in an application where I need to initialize some coordinates to an array and I wound up using nested for-in loops to accomplish the task.

Is there is a better way to accomplish this?

class Coord {

    let xVal : Int
    let yVal : Int

    init(x: Int, y: Int) {
        xVal = x
        yVal = y
    }
}

var coord = [Coord]()

for xVal in 0...20 {
    for yVal in 0...20 {
        coord.append(Coord(x: xVal, y: yVal))
    }
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

What you have is fine. If you wanted to use a functional approach and avoid making coord be mutable you could use flatMap and map:

let indexes = 0...20
let coord = indexes.flatMap { (xVal:Int) -> [Coord] in
    indexes.map { (yVal:Int) -> Coord in
        Coord(x: xVal, y: yVal)
    }
}

If you are familiar with lambda expressions then you may know that this can be simplified to this:

let indexes = 0...20
let coord = indexes.flatMap { x in indexes.map { Coord(x: x, y: $0) } }

If all you are doing with Coord is storing coordinates, you may consider just using Tuples:

let coord = indexes.flatMap { xVal in indexes.map { yVal in (xVal, yVal) }}
\$\endgroup\$
2
  • \$\begingroup\$ This is exactly what I was hoping for, thank you kindly \$\endgroup\$ Commented Nov 27, 2015 at 22:52
  • \$\begingroup\$ Great explanation! \$\endgroup\$
    – Tobonaut
    Commented Dec 1, 2015 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.