UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Unsure of how to create a fixed number of structs in a class, and updating them individually

Forums > SwiftUI

I am building an app that is aimed to assist users to follow a 28-day quit smoking challenge, and the way Im planning to build it is by creating an DaysList class array, consisting of 28 Day structs, which are meant to be updated on a daily basis, but I'm unsure of how to build it. How do I go about building that?

2      

As you planning to have a fixed number of days, 28, you can use the repeating feature of arrays.

You will also have write your own methods for the functions. I have assumed some types for the struct, and you will need to consider what is appropriate for your app. I hope that this gives you some food for thought.

class DaysList {

    struct someEntity: Identifiable {  // may need other protocols Hashable, Codable, depending on the design

        var id: UUID
        var dayNumber: Int
        var thingsToDo : String

        init(dayNumber: Int, thingsToDo: String) {
            self.dayNumber = dayNumber
            self.thingsToDo = thingsToDo
            self.id = UUID()
        }
    }

    @Published var course = [someEntity] (repeating: DaysList.someEntity.init(dayNumber: 0, thingsToDo: ""), count: 28 )

    // write your own methods for this class, for example substitute 0 in the array with 1, 2, 3, . . . , 27 for dayNumber
    func x () {

        // some code here
    }
}

2      

var course = [someEntity] (repeating: DaysList.someEntity.init(dayNumber: 0, thingsToDo: ""), count: 28 )

This will actually give you 28 copies of the same struct, with the same dayNumber and id. Probably not what is desired.

Try this:

var course: [SomeEntity] = Array(1...28).map { SomeEntity(dayNumber: $0, thingsToDo: "") }

This will create a new SomeEntity struct 28 times, with the dayNumber incremented and a separate id for each one.

2      

Oh damn! I've heeded both your advices and somewhat got it working! Thanks you very much, I appreciate it!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.