TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Question: How do I put this in core data and fetch it later for the user?

Forums > SwiftUI

Hello everyone! I'm trying to build a multiple choice quiz app for fun. Recently, I've been struggling with core data and how to put the results (score) the user got. I'm trying to build a view where the user can look at their score that they got. Any pointers on how to put the info below into coredata? Any help would be appreciated!

This is my view for what the user got:

import SwiftUI struct ResultsView: View { let viewModel: ResultsViewModel var body: some View { VStack { HStack {

        Text("Final Score:")
            Text(viewModel.finalPercentText)
        Text("Letter Grade:")
            Text(viewModel.letterGradeText)
                                    }
        .padding()

            .padding()
            .font(.system(size:30))
        Text(viewModel.correctSelectionText)
            .padding()
            .font(.system(size:30))
        Text(viewModel.incorrectSelectionText)
            .font(.system(size:30))
            .padding()
        Spacer()
       NavigationLink (
        destination: ContentView(),
        label: {
            BottomText(str: "Return Home")
                .padding(.bottom)
        }) }
    .navigationBarHidden(true)
                }

struct ResultsView_Previews: PreviewProvider { static var previews: some View { NavigationView { ResultsView(viewModel: ResultsViewModel(selectionCount: (99,7))) } } } }

This is the view Model:

import Foundation

struct ResultsViewModel { let selectionCount: (correct: Int, incorrect: Int)

var finalPercentText: String {
    "\(score) %"
}
var letterGradeText: String {
    switch score {
    case 90...100: return "A"
    case 80..<90: return "B"
    case 70..<80: return "C"
    case 60..<70: return "D"
    case 0..<60: return "F"
    default: return "?"
    }

}
var correctSelectionText: String {
    "\(selectionCount.correct) ✅"
}
var incorrectSelectionText: String {
    "\(selectionCount.incorrect) ❌"

}

private var score: Int {
    selectionCount.correct * 100 / (selectionCount.correct + selectionCount.incorrect)
}

}

3      

Please give us an idea of where you are in the HackingWithSwift lessons. Are you following 100 Days of SwiftUI?

On Day 53, @twostraws introduces Core Data. If you're following along, it would be helpful to know which day, which video, or which lesson is a bit confusing for you. Without this context, your question above looks like you're casting a general cry of help asking us to design your core data solution for you.

You want the skills to do this on your own!

Big Problem = Lots of Small Problems

First bit of advice, take your BIG problem and break it down into lots of smaller, solvable problems.

Your question above is a jumble of thoughts and concepts. You ask for CoreData advice, yet show us no CoreData code.

If fact, all you've provided is view code. That is, you are showing only parts of what your users see and interact with. But you do not describe any of your data!

Take two sheets of paper and lay them side by side on your desk. Write "Quiz Data" at the top of one, and "User Interface" at the top of the other. It might help you to write "CoreData. No interface stuff." under "Quiz Data". Plus you might add "Just show data." under "User Interface".

Now jot down some notes. What data do you want to collect over the life of a quiz? Valid Questions? Possible answers? Do you want to collect names, classroom number, topic for each quiz taker? Do you want to record their answers for each question? Assemble these into logical groupings (Student, Questions, Categories, Quiz).

Look for relationships. For example a quiz may have an ID ("Q219"), a topic ("Italian Verbs"), a date given ("12 January 2022"), and a list of questions( #12, #15, #122, #202, #8, #42). The questions may have an id (#42), a question ("Cantare means:"), and four possible answers ("1. I can't", "2. Put into cans", "3. Sing a song", "4. Lean to one side."). The question entity must also record which of the four options is the correct answer! (#3. Sing a song"). Now take a close look. Your Quiz object must have one, possibly many Question objects. For example, quiz Q210 has several questions. We see one of these is #42. Define these relationships, you'll need them in CoreData. Your Student object will have one, possibly many quizzes.

These are all design considerations you should focus on before you write any code! Also note, none of the elements on the Quiz Data sheet should influence how it looks on an iPad, or iPhone screen. You are just noodling through the data you want to save for future reference.

These design decisions will help you design Swift structures to hold the data you want to store in CoreData. It's important that you follow HWS videos because you'll see that your structs should implement important protocols such as Codable, and Identifiable. If you're not familiar with these concepts and protocols, you'll have a bad time with CoreData. Jes' sayin'.

The other sheet, User Interface, is a bit more fun because you can add colors, and icons, and fart sound effects. But each visual and audible element should only reflect the data from your Quiz Data sheet. If you have an idea for spacing, or font, or color, write it down on the User Interface page. If you want to store it and pull it up a few days, or few years later (Total Score, Average Score for Italian Verbs, Question Most Students Get Wrong) write this down on the Quiz Data sheet. Again, the 100 Days videos cover these concepts step-by-step.

Tell us! Which step are you on?

3      

Please edit your question above, and place ALL YOUR CODE inside the backtick marks!

Some of your code is outside the marks, making it hard to read.

One of the forum's regular contributors provides a great explanation on how to do this here.

Formatting Code in HWS Forums

3      

Hello! Sorry for the late response; I didn't expect to get a response this early haha. I realized how vague I made my question and I deep apologize for it. I meant to ask for what entites would you think I should need (which you conveniently answered!) and how you think I should connect the score with the core data.

As for where I am on HWS; I've mainly been "cherry-picking" the info I need (which is obviously not working for me), so I will start taking a look at the core data videos!

Finally, sorry for the awful format! Looking back I realize how carelessly I wrote the question!

3      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.