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!
Voce ta na pagina em português. This question was supposed to be posted on the main page
– Leo Dabus
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
– Leo Dabus
@Leodabus I’m new here and I didn’t pay attention to it. And thank you so much for your help! That’s right!
– outrowender
Swift 3 in the dictionary type you should use Any instead of Anyobject
[String: Any]
and preferably using conditional castas?
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.– Leo Dabus
Thanks for the tip @Leodabus!
– outrowender