/
QuestionsListModel.swift
54 lines (47 loc) · 1.29 KB
/
QuestionsListModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//
// QuestionsListModel.swift
// WatchQuizApp WatchKit Extension
//
// Created by Gualtiero Frigerio on 11/07/2019.
// Copyright © 2019 Gualtiero Frigerio. All rights reserved.
//
import Combine
import SwiftUI
enum AnswerType {
case correct
case wrong
case unanswered
}
class QuestionsListModel : ObservableObject {
var willChange = PassthroughSubject<Void, Never>()
var questions:[Question]
var category:Category
private var answers:[Int:AnswerType] = [:]
init(category:Category) {
self.category = category
self.questions = category.questions
}
func getAnswer(forQuestionId id:Int) -> AnswerType {
if let answer = answers[id] {
return answer
}
return .unanswered
}
func getQuestion(id:Int) -> Question? {
for question in questions {
if question.id == id {
return question
}
}
return nil
}
func setAnswer(_ answer:String, forQuestionId id:Int) {
willChange.send()
for index in 0..<questions.count {
if questions[index].id == id {
let type:AnswerType = questions[index].correctAnswer == answer ? .correct : .wrong
answers[id] = type
}
}
}
}