List append on for loop - Swift 3 / Xcode 8

Asked

Viewed 78 times

1

I’m having a problem Adding items to a list Inside the 'for' loop, Where all items in the list are repeated with the last value entered.

Here is my Nsmanagedobject list

 var  listCursosNovos: [Cursos] = []

Here is my loop:

for i in 0..<JSON.count{
  var resultadoWS = JSON[i] as [String:AnyObject]!

  curso.codcurso = resultadoWS?["COD_CURSO"] as? String

  //Here I see that 'curso' comes as I wanted it  
  print("Add curso: ",curso)

self.listCursosNovos.append(curso) //Here is the problem
}

Each 'stroke' item is Shown to me on the console and Everything Works fine. The problem is that when I put this item in the list, it repeats the last value I entered. Example:

If I have 3 items Within 'JSON' with the values:

{codcurso = "Zezinho"}
{codcurso = "Huginho"}
{codcurso = "Luizinho"}

After Getting out of the loop and checking the result of my list

print("The final list is:",self.listCursosNovos)

They look like this:

{codcurso = "Luizinho"}
{codcurso = "Luizinho"}
{codcurso = "Luizinho"}

This is repeated regardless of how Many items I have Inside 'JSON' and the value repeated is Always the last, I can’t understand Why

I Hope someone can help me. Thank you!

  • 1

    Voce ta na pagina em português. This question was supposed to be posted on the main page

  • Voce needs to create a new object (course) each time you add it to the array within the loop. Currently Voce ta adding the same object in its 3x array

  • 1

    @Leodabus I’m new here and I didn’t pay attention to it. And thank you so much for your help! That’s right!

  • Swift 3 in the dictionary type you should use Any instead of Anyobject [String: Any] and preferably using conditional cast as? and adds nil coalescing Operator at the end ?? [:] so your app doesn’t crash in case the cast fails simply it passes an empty dictionary.

  • 1

    Thanks for the tip @Leodabus!

1 answer

0


As a user here helped me, the Solution was to create a new 'Course' type Object with each loop. I Did not pay Attention to this and was Creating it before entering my loop

for i in 0..<JSON.count{
  var resultadoWS = JSON[i] as [String:AnyObject]!
  let curso = Cursos(context: contexto)//Here is the solution

  curso.codcurso = resultadoWS?["COD_CURSO"] as? String

  //Here I see that 'curso' comes as I wanted it  
  print("Add curso: ",curso)

self.listCursosNovos.append(curso)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.