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

SOLVED: Why am I getting the "Return from initializer without initializing all stored properties" error message?

Forums > SwiftUI

I am new to swiftui and am trying to use UserDefaults to persist information. I have a class which has all the arrays that i want to save the information with, but when I try to initialise the variables using UserDefaults, it prints out the "Return from initializer without initializing all stored properties" error message. Can someone explain why this is?

Here is my code:

class globalHW: ObservableObject {

    @Published var hwInput : [hw] { didSet { saveIn() } }
    @Published var hwShow : [hw] { didSet { saveShow() } }

    let hwInputKey: String = "hwInputKey"
    let hwShowKey: String = "hwShowKey"

    let defaultInput = UserDefaults.standard
    let defaultShow = UserDefaults.standard
    let encoder = JSONEncoder()

    init() {
        let decoder = JSONDecoder()

        if let savedInput = defaultInput.object(forKey: hwInputKey) as? Data {
            if let lodadedInput = try? decoder.decode([hw].self, from: savedInput) {
                print(lodadedInput)
                self.hwInput = lodadedInput
            }
        }

        if let savedShow = defaultInput.object(forKey: hwShowKey) as? Data {
            if let loadedShow = try? decoder.decode([hw].self, from: savedShow) {
                print(loadedShow)
                hwShow.self = loadedShow
            }
        }

    }

    func saveIn() {
        if let encoded = try? encoder.encode(hwInput) {
            defaultInput.set(encoded, forKey: hwInputKey)
        }
    }

    func saveShow() {
        if let encoded = try? encoder.encode(hwShow) {
            defaultShow.set(encoded, forKey: hwShowKey)
        }
    }

}

2      

Hi, You are getting the error message because if any of the if let fail the properties would not be initialized.

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!

Reply to this topic…

You need to create an account or log in to reply.

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.