NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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?


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
   = 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


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.


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


Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

Reply to this topic…

You need to create an account or log in to reply.

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.