WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Challenge Day 47 - property 'habit' is a 'let' error

Forums > 100 Days of SwiftUI

I'm doing the challenge and I an getting this error when trying to assign a date to a property

struct ContentView: View {
  @State private var habits: [Habit] = []//Habit.examples()

  var body: some View {
    NavigationStack {
      List {
        ForEach(habits, id: \.name) { habit in
          HStack {
            VStack(alignment: .leading) {
              Text(habit.name)
                .font(.headline)
              Text("\(habit.addedDate.convertToMonthDayYear())")
                .font(.caption)
            }
            Spacer()
            Image(systemName: habit.completedToday ? "checkmark.square.fill" : "square")
              .resizable()
              .scaledToFit()
              .foregroundStyle(Color("tintColor"))
              .frame(width: 25, height: 25)
              .onTapGesture {
                habit.lastCompletionDate = Date()
              }
          }
        }
        .navigationTitle("Daily Habits")
        .padding()
      }
      .onAppear {
        populateHabits()
      }
    }
  }

This is the habit struct

struct Habit {
  let id = UUID()
  var name: String
  var attempts: Int = 0 // frequency
  var queue: String?
  var response: String?
  var reward: String?
  var tags: [Tag] = []
  let addedDate = Date()
  var lastCompletionDate: Date?

  var completedToday: Bool {
    let today = Date.now.convertToMonthDayYear()
    guard let date = lastCompletionDate else {
      return false
    }

    if date.convertToMonthDayYear() == today { return true }
    return false
  }

  static func example() -> Habit {
    Habit(name: "Learning SwiftUI")
  }

  static func examples() -> [Habit] {
    return [
      .init(name: "Learning Swift"),
      .init(name: "Drawing", lastCompletionDate: Date()),
      .init(name: "Learn Raspberry Pi"),
      .init(name: "Excercise")
    ]
  }
}

   

@Chuck has a bad habit...

I am getting this error when trying to assign a date to a property

// ---------------------------👇🏼 Here! SwiftUI makes a copy.
ForEach(habits, id: \.name) { habit in
    HStack {
        VStack(alignment: .leading) {
           Text(habit.name) // 👈🏼 Here you show the name of the COPY.
           Text("\(habit.addedDate.convertToMonthDayYear())")
         }
         Image(systemName: habit.completedToday ? "checkmark.square.fill" : "square")
             // ...snip.....
              .onTapGesture {
              // 👇 Here! You are trying to change the date of an unmutable copy.
                habit.lastCompletionDate = Date()
              }
          }

View Factory

I like to think of ForEach() as a factory. It's job is to take some parts and build several views for you. In your code above, the ForEach()is building an HStack() with some content.

Your factory requires a habit to assemble the parts inside the HStack(). It's an important skill for you to recognize that you are passing in one habit at a time from your habits collection. But when you hand a single habit to the ForEach() factory manager, you are NOT providing the actual habit. Instead you are providing an (unchangable!) copy of the habit.

Keep Coding

Some other descriptions of the ForEach()factory.

See -> View Factory
or See -> View Factory
or See -> View Factory

So, ask yourself: In the code snip above what is the ForEach view factory trying to make?

   

Thanks for the reply! I forgot to make the Habit model a class. I keep forgetting that structs are new instances and classes are the same object for every copy if it.

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.