Array and UserDefault

I am making a Quiz app, but I’ve gotten a bit stuck where I am now. This is the class for the quiz questions:

import Foundation

struct Question: Codable {
    let level: Int
    let image: String
    let answers: [String]
    var complete: Bool
    let type: String // This can be used as the category if needed

    init(level: Int, image: String, answers: [String], complete: Bool, type: String) {
        self.level = level
        self.image = image
        self.answers = answers
        self.complete = complete
        self.type = type
    }
}

class AllQuestions {
    
    static let shared = AllQuestions()
    
    var questions: [Question] = []
    
    private init() {}
    
    func countCompletedQuestions(forType type: String) -> Int {
        return questions.filter { $0.type == type && $0.complete }.count
    }
    
    // Load questions from UserDefaults when the app starts
    func loadQuestions() {
        if let savedQuestions = UserDefaults.standard.data(forKey: "savedQuestions"),
           let decodedQuestions = try? JSONDecoder().decode([Question].self, from: savedQuestions) {
            questions = decodedQuestions
            print("Questions loaded successfully.")
        } else {
            loadDefaultQuestions()
            loadFlagQuestions()
            loadCarBrandQuestions()
            saveQuestions() // Save the default questions initially
        }
    }
    
    // Update question completion state and save changes to UserDefaults
    func updateQuestionCompletion(forQuestion question: Question) {
        guard let index = questions.firstIndex(where: { $0.level == question.level && $0.image == question.image && $0.answers == question.answers }) else {
            print("Question not found.")
            return
        }
        questions[index].complete = true
        saveQuestions()
        print("Question updated successfully.")
    }
    
    // Save all questions to UserDefaults
    func saveQuestions() {
        guard !questions.isEmpty else {
            print("Questions array is empty. Nothing to save.")
            return
        }
        
        if let encodedQuestions = try? JSONEncoder().encode(questions) {
            UserDefaults.standard.set(encodedQuestions, forKey: "savedQuestions")
            print("Questions saved successfully.")
        } else {
            print("Failed to encode questions.")
        }
    }
    
    // Example method to mark a question as complete
    func markQuestionAsComplete(atIndex index: Int) {
        guard index >= 0, index < questions.count else {
            return
        }
        questions[index].complete = true
        saveQuestions()
    }
    
    func resetQuestions() {
        for index in 0..<questions.count {
            questions[index].complete = false
        }
        saveQuestions()
    }
    
    func loadDefaultQuestions() {
        questions = [
            // Level 1
            Question(level: 1, image: "FACEBOOK", answers: ["FACEBOOK", "FB"], complete: false, type: "CLASSIC"), // 1
            Question(level: 1, image: "SNAPCHAT", answers: ["SNAPCHAT"], complete: false, type: "CLASSIC"), // 2
            Question(level: 1, image: "INSTAGRAM", answers: ["INSTAGRAM"], complete: false, type: "CLASSIC"),// 3
            Question(level: 1, image: "MESSENGER", answers: ["MESSENGER"], complete: false, type: "CLASSIC"), // 4
            Question(level: 1, image: "WHATSAPP", answers: ["WHATSAPP"], complete: false, type: "CLASSIC"), // 5
            Question(level: 1, image: "YOUTUBE", answers: ["YOUTUBE"], complete: false, type: "CLASSIC"), // 6
            Question(level: 1, image: "VINE", answers: ["VINE"], complete: false, type: "CLASSIC"), // 7
            Question(level: 1, image: "SKYPE", answers: ["SKYPE"], complete: false, type: "CLASSIC"), // 8
            Question(level: 1, image: "LINKEDIN", answers: ["LINKEDIN"], complete: false, type: "CLASSIC"), // 9
            Question(level: 1, image: "TWITCH", answers: ["TWITCH"], complete: false, type: "CLASSIC"), // 10
            Question(level: 1, image: "TWITTER", answers: ["TWITTER"], complete: false, type: "CLASSIC"), // 11
            Question(level: 1, image: "TIKTOK", answers: ["TIKTOK"], complete: false, type: "CLASSIC"), // 12
            Question(level: 1, image: "OUTLOOK", answers: ["OUTLOOK"], complete: false, type: "CLASSIC"), // 13
            Question(level: 1, image: "GMAIL", answers: ["GMAIL", "GOOGLE MAIL"], complete: false, type: "CLASSIC"), // 14
            Question(level: 1, image: "AMAZON", answers: ["AMAZON"], complete: false, type: "CLASSIC"), // 15
            
            // Level 2
            Question(level: 2, image: "PLAYSTATION", answers: ["PLAYSTATION"], complete: false, type: "CLASSIC"), // 1
            Question(level: 2, image: "PAYPAL", answers: ["PAYPAL"], complete: false, type: "CLASSIC"), // 2
            Question(level: 2, image: "SPOTIFY", answers: ["SPOTIFY"], complete: false, type: "CLASSIC"),// 3
            Question(level: 2, image: "NETFLIX", answers: ["NETFLIX"], complete: false, type: "CLASSIC"), // 4
            Question(level: 2, image: "PHOTOSHOP", answers: ["PHOTOSHOP"], complete: false, type: "CLASSIC"), // 5
            Question(level: 2, image: "BMW", answers: ["BMW"], complete: false, type: "CLASSIC"), // 6
            Question(level: 2, image: "QUICKTIME", answers: ["QUICKTIME"], complete: false, type: "CLASSIC"), // 7
            Question(level: 2, image: "VLC", answers: ["VLC"], complete: false, type: "CLASSIC"), // 8
            Question(level: 2, image: "KIK", answers: ["KIK"], complete: false, type: "CLASSIC"), // 9
            Question(level: 2, image: "TUMBLR", answers: ["TUMBLR"], complete: false, type: "CLASSIC"), // 10
            Question(level: 2, image: "ANDROID", answers: ["ANDROID"], complete: false, type: "CLASSIC"), // 11
            Question(level: 2, image: "APPLE", answers: ["APPLE"], complete: false, type: "CLASSIC"), // 12
            Question(level: 2, image: "CHROME", answers: ["CHROME"], complete: false, type: "CLASSIC"), // 13
            Question(level: 2, image: "FIREFOX", answers: ["FIREFOX"], complete: false, type: "CLASSIC"), // 14
            Question(level: 2, image: "ITUNES", answers: ["ITUNES"], complete: false, type: "CLASSIC"), // 15
        ]
    }
    
    func loadFlagQuestions() {
        let flagQuestions = [
            // Level 1
            
            Question(level: 1, image: "flag_norway", answers: ["NORWAY", NORGE"], complete: false, type: "FLAGS"),// 1
            Question(level: 1, image: "flag_sweden", answers: ["SWEDEN", "SVERIGE"], complete: false, type: "FLAGS"),// 2
            Question(level: 1, image: "flag_england", answers: ["ENGLAND", "ENGLAND"], complete: false, type: "FLAGS"),// 3
            Question(level: 1, image: "flag_australia", answers: ["AUSTRALIA"], complete: false, type: "FLAGS"),// 30
            Question(level: 1, image: "flag_brazil", answers: ["BRAZIL", "BRASIL"], complete: false, type: "FLAGS"),// 4
            Question(level: 1, image: "flag_bulgaria", answers: ["BULGARIA", "BULGARIA"], complete: false, type: "FLAGS"),// 5


        ]
        
        questions.append(contentsOf: flagQuestions)
    }
    
    func loadCarBrandQuestions() {
        let carBrandQuestions = [
            // Level 1
            
            Question(level: 0, image: "car_jaguar", answers: ["JAGUAR"], complete: false, type: "CAR BRANDS"), // 1
            Question(level: 0, image: "car_audi", answers: ["AUDI"], complete: false, type: "CAR BRANDS"), // 2
            Question(level: 0, image: "car_bmw", answers: ["BMW"], complete: false, type: "CAR BRANDS"), // 3
            Question(level: 0, image: "car_ford", answers: ["FORD"], complete: false, type: "CAR BRANDS"), // 4
            Question(level: 0, image: "car_ferrari", answers: ["FERRARI"], complete: false, type: "CAR BRANDS"), // 5
        ]
        
        questions.append(contentsOf: carBrandQuestions)
    }
}

And AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        // Load questions once the app starts
        AllQuestions.shared.loadQuestions()
        
        return true
    }

So all the Questions load fine and all, the complete boolean changed to true when the user has completed the question, but because of the if let in the loadQuestions function, the Questions will only be loaded.

But later I will need to add some more Questions after the app has been launched? And again, because of the if let in the loadQuestions, the Questions will be loaded from the UserDefault each time, so newly added questions will never be loaded.

Any suggestions?

New contributor

Kimberly is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật