# Mapping multiple values to an array object

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


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

• This is exactly what I was hoping for, thank you kindly Commented Nov 27, 2015 at 22:52
• Great explanation! Commented Dec 1, 2015 at 14:29