class - Swift For In Loop Iterating Through an Array of Custom Classes Doesn't Work -
i working project , have come across error when iterating through in loop 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) _class in myarray.indices { myarray[_class].namenum = _class } print("\n") _class in myarray.indices { print("item \(_class): \(myarray[_class].name)") }
i following output:
item 0: customclass 4
item 1: customclass 4
item 2: customclass 4
item 3: customclass 4
item 4: customclass 4
this not make sense me thought following output instead:
item 0: customclass 0
item 1: customclass 1
item 2: customclass 2
item 3: customclass 3
item 4: customclass 4
any why doesn't work or how go fixing appreciated, thanks!
you should change array initialization
var myarray : [customclass] = (0..<5).map { _ in customclass() }
from
var myarray : [customclass] = [customclass](repeating: customclass(), count: 5)
complete code:
class customclass { var namenum : int { didset { self.name = "customclass \(namenum)" } } var name : string init() { namenum = 0 self.name = "customclass \(namenum)" } } var myarray : [customclass] = (0..<5).map { _ in customclass() } _class in myarray.indices { myarray[_class].namenum = _class } print("\n") _class in myarray.indices { print("item \(_class): \(myarray[_class].name)") }
the reason code, creates instance of customclass
, adds @ 5 indexes of array expecting 5 different instance of customclass
. if same instance added 5 times, of them have last set value in case 4.
item 0: customclass 0
item 1: customclass 1
item 2: customclass 2
item 3: customclass 3
item 4: customclass 4
Comments
Post a Comment