UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Fail to encode object to save it into UserDefaults

Forums > Swift

Hi everyone !

I'm trying to save a custom object into the UserDefaults but it sounds like the JSONEncoder don't encode correctly my object. Take a look at my object structure:

struct Language: Identifiable, Codable {
    @DocumentID var id: String?
    var code: String
    var localizedName: String? {
        return localizedStringFromCode()
    }

    init?(id: String?, code: String?) {
        guard let code = code else { return nil }
        self.id = id
        self.code = code
    }

    private func localizedStringFromCode() -> String? {
        return Locale.current.localizedString(forLanguageCode: self.code)
    }
}

To encode this object, I just followed the example here

Here is how I try to encode my custom object:

var sourceLanguage: Language? {
        set {
            if let value = newValue {
      // The if let below fails due to encode failure
                if let encodedLanguage = try? encoder.encode(value) {
                    UserDefaults.standard.set(encodedLanguage, forKey: "SourceLanguage")
                }
            }
        }

        get {
            if let savedLanguage = UserDefaults.standard.object(forKey: "SourceLanguage") as? Data,
               let loadedLanguage = try? decoder.decode(Language.self, from: savedLanguage) {
                return loadedLanguage
            } else {
                return nil
            }
        }
    }

I thanks you a lot in advance and I hope you'll help me solve my problem. Have a nice day !

2      

What is the encoding error you're getting?

2      

I'm not getting any error because I do "if let". But this line:

try? encoder.encode(value)

returns nil.

Apparently, the encoder failed to encode my value. I wonder if the problem is about my object structure or something else.

Thanks a lot !

2      

Instead of masking the error with try? do this:

do {
    let encodedLanguage = try encoder.encode(value)
    UserDefaults.standard.set(encodedLanguage, forKey: "SourceLanguage")
}
catch {
    print(error)
}

That will let you see what the error is. It's hard to know how to correct it if you don't know what's going wrong.

2      

Thank you for the tip ! Here is the error:

("DocumentID values can only be encoded with Firestore.Encoder")

This is because I use Firebase Firestore. So I think I will have to implement customs encoder and decoder initializers. Do you confirm ?

2      

I've never worked with Firestore so I can't say.

Maybe this would be useful: Mapping Firestore Data in Swift - The Comprehensive Guide

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.