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

SOLVED: Day 47: Error when saving new activity

Forums > 100 Days of SwiftUI

I've got the following error when saving a new activity, and can't get it fixed.

"Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

Here's my code:

struct Activity: Identifiable, Equatable, Hashable
{
    let id = UUID()
    var title: String
    var description: String
    var count: Int = 0
}

class Activities: ObservableObject
{
    @Published var items = [Activity]()
}

struct ContentView: View {
    @ObservedObject var activities = Activities()

    @State private var showingNewActivityScreen = false

    var body: some View {
        NavigationView {
            VStack {
                ForEach(activities.items) { activity in
                    HStack {
                        Text("\(activity.title)")
                            .frame(minWidth: .infinity)
                            .padding()
                            .background(Color.blue)
                            .foregroundColor(Color.white)
                            .clipShape(RoundedRectangle(cornerRadius: 16))

                        Spacer()

                        Text("\(activity.count)").padding(.horizontal)
                        Button(action: {
                            let currentTrackerIndex = self.activities.items.firstIndex { $0 == activity }
                            if let index = currentTrackerIndex { self.activities.items[index].count += 1 }
                        }) { Image(systemName: "plus").padding() }
                    }
                }
            }
            .navigationBarTitle("Habit Tracking")
            .navigationBarItems(trailing:
                Button(action: { self.showingNewActivityScreen = true },
                       label: { Text("New") } )
            )
        }
        .sheet(isPresented: $showingNewActivityScreen, content: { RegisterActivity(activities: self.activities, "New activity") })
    }
}

struct RegisterActivity: View {
    @ObservedObject var activity: Activities
    @Environment(\.presentationMode) var presentationMode

    @State private var title = ""
    @State private var description = ""

    let screenTitle: String

    var body: some View {
        VStack {
            HStack {
                Text("Title")
                TextField("Title", text: $title)
            }.padding()
            HStack {
                Text("Description")
                TextField("Description", text: $description)
            }.padding()
            HStack {
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("Cancel").padding()
                }
                Spacer()
                Button(action: {
                    self.activity.items.append(Activity(title: self.title, description: self.description))
                    //print("\(self.trackers.items)")
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("Save").padding()
                }
            }
        }.navigationBarTitle("New Activity")
    }

    init(activities: Activities, _ screenTitle: String = "New Item")
    {
        self.activity = activities
        self.screenTitle = screenTitle
    }
}

I can't spot what's wrong. Something in the ForEach maybe? Is it how I use the Observable/Observed thing? Any clues?

3      

hi,

this was a tough one to spot. you had

// inside the ForEach
Text("\(activity.title)")
  .frame(minWidth: .infinity) // <-- this is the problem
  // and other qualifiers

did you mean .frame(maxWidth: .infinity) ?

(also, did you want a simple VStack or a List?)

hope that helps,

DMG

4      

Thank you @delawaremathguy. This is the exact solution I got at the slack channel for this forum (including the VStack vs List thing 😂)

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.