I have a multidimensional (2D) array of items (object) and I decided to use the "natural" way to create it (so instead of using the trick to transform a 1D array into 2D, I go 2D directly).
An item has a X & Y position on the matrice and the item has also a random type.
Everything seems to work except for the Y position of all the items... Because of how Swift handles 2D, I needed to initialize the 2D array then affect the values correctly to each item.
I do verify the value that I affect to the items, they work. Then when I verify the item after it has been correctly set, the Y position is like unique to all the items.
class Matrix {
var nbCol: Int
var nbRow: Int
var items: [[Item]]
init(nbCol: Int, nbRow: Int) {
self.nbCol = nbCol
self.nbRow = nbRow
items = Array<Array<Item>>()
//Initialize
for col in 0..<Int(nbCol) {
items.append(Array(count: nbRow, repeatedValue: Item()))
}
//Affect the correct values to each item
createItems()
}
func createItems() {
//Assign X, Y & type values to the item
for x in 0..<Int(nbCol) {
for y in 0..<Int(nbRow) {
items[x][y].setItem(x, y: y, type: ItemType.random())
println("Create for (\(x), \(y)): (\(items[x][y].x), \(items[x][y].y))")
}
}
//Verify the values
for x in 0..<Int(nbCol) {
for y in 0..<Int(nbRow) {
println("Check for (\(x), \(y)): (\(items[x][y].x), \(items[x][y].y))")
}
}
}
}
And Item (part of it) is :
class Item: Printable {
var x: Int
var y: Int
var type: ItemType //Enum
func setItem(x: Int, y: Int, type: ItemType) {
self.x = x
self.y = y
self.type = type
}
}
And the output (with the problem in red):

As you can see, during "setting values", X & Y are correct. But at check, only X is correct and Y is "stuck". Am I doing something wrong ?
EDIT : By the way, all items has also the same type. Only X is correct, Y & type are "fixed" for all items.