sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.85k stars 365 forks source link

Type does not conform to protocol 'DefaultsSerializable' #206

Closed CoderMaurice closed 4 years ago

CoderMaurice commented 4 years ago
class NotificationMessage: Codable, DefaultsSerializable {
    var type: MessageType = .normal
}

//  Error: Type 'MessageType' does not conform to protocol 'DefaultsSerializable'
enum MessageType: Int, Codable, DefaultsSerializable {
    case normal   = 1
    case activity    = 2 
}

why i get this error?

sunshinejr commented 4 years ago

Hey @CoderMaurice - this is a very good question. So how does SwiftyUserDefaults work is that it synthesizes the bridges needed to fetch/store objects (most of the time). So we synthesize these bridges for both Codable and RawRepresentable protocols. Unfortunately, when you have both of these the compiler is confused and don't know which synthesized bridges do you want for the object - the ones for RawRepresentable or for Codable.

The difference between these is how the object is stored underneath, in a plist. Depending on your preference, you should use the following:

enum MessageType: Int, Codable, DefaultsSerializable {
    case normal   = 1
    case activity    = 2 

    public static var _defaults: DefaultsBridge<MessageType> { return __YOUR_BRIDGE__ }
    public static var _defaultsArray: DefaultsBridge<[MessageType]> { return __YOUR_ARRAY_BRIDGE__ }

where:

Let me know if it helped!

CoderMaurice commented 4 years ago

Thanks very much for your reply, now it works as expected.

sunshinejr commented 4 years ago

Awesome, glad it helped! 🚀

mortenholmgaard commented 3 years ago

This is how the code looks in using the latest version: (it took me a while to figure out)

public static var _defaults: DefaultsRawRepresentableBridge< MessageType> { DefaultsRawRepresentableBridge< MessageType>() }
public static var _defaultsArray: DefaultsRawRepresentableArrayBridge<[MessageType]> { DefaultsRawRepresentableArrayBridge<[MessageType]>() }
antonyjamese commented 2 years ago

This is how the code looks in using the latest version: (it took me a while to figure out)

public static var _defaults: DefaultsRawRepresentableBridge< MessageType> { DefaultsRawRepresentableBridge< MessageType>() }
public static var _defaultsArray: DefaultsRawRepresentableArrayBridge<[MessageType]> { DefaultsRawRepresentableArrayBridge<[MessageType]>() }

@mortenholmgaard let's say MessageType we are going to use is an optional one, can you also please share how to represent the optional data?

mortenholmgaard commented 2 years ago

@antonyjamese It does not solve the problem for us with the latest version of xCode - I think the problem you/we are experiencing now is related to: https://github.com/sunshinejr/SwiftyUserDefaults/issues/288