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))

1 Answer 1


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) }}
  • \$\begingroup\$ This is exactly what I was hoping for, thank you kindly \$\endgroup\$ Nov 27, 2015 at 22:52
  • \$\begingroup\$ Great explanation! \$\endgroup\$
    – Tobonaut
    Dec 1, 2015 at 14:29

Your Answer

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

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