ios - Multidimensional array of objects bug in swift? -


i have multidimensional (2d) array of items (object) , decided use "natural" way create (so instead of using trick transform 1d array 2d, go 2d directly).

an item has x & y position on matrice , item has random type.

everything seems work except y position of items... because of how swift handles 2d, needed initialize 2d array affect values correctly each item.

i verify value affect items, work. when verify item after has been correctly set, y position unique 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         col in 0..<int(nbcol) {             items.append(array(count: nbrow, repeatedvalue: item()))         }         //affect correct values each item         createitems()     }      func createitems() {         //assign x, y & type values item         x in 0..<int(nbcol) {             y in 0..<int(nbrow) {                 items[x][y].setitem(x, y: y, type: itemtype.random())                 println("create (\(x), \(y)): (\(items[x][y].x), \(items[x][y].y))")             }         }         //verify values         x in 0..<int(nbcol) {             y in 0..<int(nbrow) {                 println("check (\(x), \(y)): (\(items[x][y].x), \(items[x][y].y))")             }         }     } } 

and item (part of it) :

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 output (with problem in red):

console output

as can see, during "setting values", x & y correct. @ check, x correct , y "stuck". doing wrong ?

edit : way, items has same type. x correct, y & type "fixed" items.

your problem repeatedvalue:item() evaluated once, not evaluated count times. means have same item in each row of given column, when set values overwriting previous 1 - why last value (2) when print it.

you need use loop populate rows rather using count/repeatedvalue construct.

init(nbcol: int, nbrow: int) {     self.nbcol = nbcol     self.nbrow = nbrow     items = array<array>()     //initialize     col in 0..<int(nbcol) {           var colarray=array<item>()            row in 0..<int(nbrow) {              colarray.append(item())           }          items.append(colarray)     }     //affect correct values each item     createitems() } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -