Top-level encoded as number JSON fragment When Using Property Wrappers

Consider the following:

@propertyWrapper struct UserDefaultsObject<T: Codable> {
    let key: String
    let defaultValue: T
    
    var wrappedValue: T {
        get {
            guard let data = UserDefaults.standard.object(forKey: key) as? Data else { return defaultValue }
            guard let value = try? JSONDecoder().decode(T.self, from: data) else { return defaultValue }
            
            return value
        }
        
        set {
            let data = try? JSONEncoder().encode(newValue)
            UserDefaults.standard.set(data, forKey: key)
        }
    }
}

@UserDefaultsObject(key: "date", defaultValue: nil)
 static var endDate: Date?

When I try this:
let now = Date()
endDate = now

I get the error: "Top-level Optional encoded as number JSON fragment."

But if I try this in Playground it succeed. I am doing something wrong ?

let now: Date? = Date()
let data = try? JSONEncoder().encode(now)

if let _ = data {
     print("success")
} else {
     print("failure")
}

I was unable to reproduce this error.

Please provide exact information about the environment in which you are getting this error. For example, what platform are you compiling for (macOS, iOS)? What version of Xcode are you using? What version of Swift are you using?

1 Like

it is fixed now !

Terms of Service

Privacy Policy

Cookie Policy