Files
QuizApp/QuizApp/ViewModel.swift
Paul ef779cf936 feat: added new CategorySelectionView
fix: progress bar will now be resetted correctly
2025-08-06 18:23:06 +02:00

77 lines
2.1 KiB
Swift

//
// ViewModel.swift
// QuizApp
//
// Created by Paul on 03.08.25.
//
import Foundation
class ViewModel: ObservableObject {
private var allQuestionsByCategory: [String: [QuizQuestion]] = [:]
@Published var questions: [QuizQuestion] = []
@Published var selectedCategory: String? = nil
@Published var currentQuestionIndex: Int = 0
@Published var score: Int = 0
@Published var isQuizFinished: Bool = false
@Published var answeredCount: Int = 0
@Published var selectedAnswers: [Int?] = []
var progress: Double {
guard !questions.isEmpty else { return 0.0 }
return Double(answeredCount) / Double(questions.count)
}
var currentQuestion: QuizQuestion? {
guard currentQuestionIndex < questions.count else { return nil }
return questions[currentQuestionIndex]
}
var availableCategories: [String] {
return Array(allQuestionsByCategory.keys).sorted()
}
init() {
guard let url = Bundle.main.url(forResource: "data", withExtension: "json") else {
questions = []
return
}
do {
let data = try Data(contentsOf: url)
allQuestionsByCategory = try JSONDecoder().decode([String: [QuizQuestion]].self, from: data)
} catch {
print("Fehler beim Laden des Inhalts: \(error)")
allQuestionsByCategory = [:]
}
}
func loadNextQuestion() {
if currentQuestionIndex + 1 < questions.count {
currentQuestionIndex += 1
} else {
isQuizFinished = true
}
}
func loadQuestions(for category: String) {
selectedCategory = category
questions = allQuestionsByCategory[category] ?? []
currentQuestionIndex = 0
score = 0
isQuizFinished = false
answeredCount = 0
selectedAnswers = Array(repeating: nil, count: questions.count)
}
func incrementScore(selectedIndex: Int) {
if let correct = currentQuestion?.correctAnswer, selectedIndex == correct {
score += 1
}
}
}