Learn Courses My Dashboard

Help with updating an array

Being new to Swift, this may be trivial for some of you, but not for me :slight_smile:

I have some arrays of the same type like:

    let club92_courseVest:[HoleDefinition] =
    [HoleDefinition(club: 92, Course: "Vest", HoleNumber: "1", imagename: "hgkvhul1", par: 5, HCP: 00, MensBackTee: 286, MensTee: 286, WomenBackTee: 286, WomenTee: 244),
    HoleDefinition(club: 92, Course: "Vest", HoleNumber: "2", imagename: "hgkvhul2", par: 4, HCP: 00, MensBackTee: 286, MensTee: 286, WomenBackTee: 286, WomenTee: 123),

I have created a func that returns the active holes, by appending multiple arrays of same structure :
before i however, can use this new array, i need to change the values in activeHoles.HoleNumber, to an increasing number from 1 to 18

The code below does not work … That would be to simple

var activeHoles:[HoleDefinition] = club92_courseNord
        activeHoles.append(contentsOf: club92_courseVest)
        var startnr = 1
        ForEach(activeHoles) { item in
            item.HoleNumber = String(startnr)
            startnr += 1
        return activeHoles

What is the easiest way to do this ???

struct HoleDefinition: Identifiable {
    var id: UUID  = UUID()
    var club: Int
    var Course:String
    var HoleNumber:String
    var imagename:String
    var par:Int
    var HCP:Int
    var MensBackTee:Int
    var MensTee:Int
    var WomenBackTee:Int
    var WomenTee:Int

You can’t do it like that because item inside your loop is a copy of the actual HoleDefinition item in the array and so changes to that copy don’t affect the item in the array.

But you can do something like this instead:

var activeHoles: [HoleDefinition] = club92_courseNord
activeHoles.append(contentsOf: club92_courseVest)
for n in activeHoles.indices {
    activeHoles[n].HoleNumber = "\(n+1)"

Also, ForEach is for use in SwiftUI Views, not for looping through any old array and doing work.

1 Like

Thanks for your answer and explanation … Worked liked a charm.