I am working a project and have come across this error when iterating through a for in loop like this:
class CustomClass {
var nameNum : Int { didSet { self.name = "CustomClass \(nameNum)" } }
var name : String
init() {
nameNum = 0
self.name = "CustomClass \(nameNum)"
}
}
var myArray : [CustomClass] = [CustomClass](repeating: CustomClass(), count: 5)
for _class in myArray.indices {
myArray[_class].nameNum = _class
}
print("\n")
for _class in myArray.indices {
print("Item \(_class): \(myArray[_class].name)")
}
I get the following output:
Item 0: CustomClass 4
Item 1: CustomClass 4
Item 2: CustomClass 4
Item 3: CustomClass 4
Item 4: CustomClass 4
This does not make sense to me as I thought I would get the following output instead:
Item 0: CustomClass 0
Item 1: CustomClass 1
Item 2: CustomClass 2
Item 3: CustomClass 3
Item 4: CustomClass 4
Any help as to why this doesn't work or to how to go about fixing it is appreciated, thanks!
_classis a misleading name in the second loop. It's actually an index