Search code examples
swiftclassiterationfor-in-loop

Swift For In Loop Iterating Through an Array of Custom Classes Doesn't Work


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!


Solution

  • You should change your array initialization to

    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() }
    
    for _class in myArray.indices {
        myArray[_class].nameNum = _class
    }
    
    print("\n")
    for _class in myArray.indices {
        print("Item \(_class): \(myArray[_class].name)")
    }
    

    The reason is that your code, actually creates an instance of CustomClass and adds it at all 5 indexes of array where as you are expecting 5 different instance of CustomClass. If the same instance is added 5 times, then all of them will have the last set value which in your case is 4.

    Item 0: CustomClass 0

    Item 1: CustomClass 1

    Item 2: CustomClass 2

    Item 3: CustomClass 3

    Item 4: CustomClass 4