Swift array reference issue -


here code:

    var productslist:[product]      switch category {     case 0:         productslist = self.sharedinstance.productslist1     case 1:         productslist = self.sharedinstance.productslist2     default:         productslist = self.sharedinstance.productslist3     }      productdic in products {         let product = product()         // set product attributes here.         productslist.append(product)     }      println(productslist)     println(self.sharedinstance.productslist1)     println(self.sharedinstance.productslist2)     println(self.sharedinstance.productslist3) 

the output:

  • productslist contains added content
  • productslist1, productslist2 , productslist3 empty.

in understanding, productslist should refer 1 of productslist1, productslist2 , productslist3 depending on category.

can explain why productslist1, productslist2 , productslist3 empty?

thanks in advance.

assigning array sharedinstance results in array being copied.

you need re-assign updated array sharedinstance array after making update.

as minimal example:

var list:[string] = []  list.append("string1") list.append("string2") list.append("string3")  var list2:[string] = list  list2.append("string4")  println(list) println(list2) 

will result in output:

"[string1, string2, string3]" "[string1, string2, string3, string4]"

you need add re-assignment lists matching:

//... list2.append("string4") list = list2 println(list) println(list2) 

you can demonstrate copy printing address of each list after assignment , showing different.

print(unsafeaddressof(list)) print(unsafeaddressof(list2)) 

or can check in debugger.

if want operate on sharedinstance copies of arrays 1 of following:

  • instead of 3 separate properties, put them in parent array property , select index in switch statement, rather new variable
  • wrap arrays in custom class, instances of passed reference.

you use nsmutablearray, although it's not best of ideas mix old , new that.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -