Codable can't synthesis OptionSet

I tried to use UIView.AnimationOptions in Codable , but found that Codable can't synthesize OptionSet automatically, but Codable can synthesize enumerate those based on RawRepresentable.

Compiler can synthesize Codable conformance for class that contains only Codable members. UIView.AnimationOptions may be OptionSet, but it's not codable. You can conform it to Codable yourself, but I won't recommend it.

But even though I conform to it, it's just simply like:

extension UIView.AnimationOptions: Decodable {
	public init(from decoder: Decoder) throws {
		try self.init(rawValue: decoder.singleValueContainer().decode(UInt.self))
	}
}

I can't figure out why the complier can't synthesize it directly.

No, it's not the compiler decision. It's the decision of the library author(s), oversight or not. The compiler will only try to synthesize the conformance if someone expresses that it conforms to the protocol. Swift won’t make a type Codable just because it has Codable members.

Also, that you use a single-value container and not a keyed container is already indicative that you want something different from what the compiler would synthesize.

What I mean is, if an enumeration based on RawRepresentable as a codable model's property can be synthesized in the model's codable function, why can't the complier synthesize OptionSet that is also based on RawRepresentable?

You'd still need to mark that enum as codable, no?

I'm not sure which one you're comparing this to since you could mean synthesis for either the raw representable enum or the type that contains raw representable enum (but not codable). Do you mean this:

enum Foo: Int { case a }
extension Foo: Codable {} // ok

or this:

enum Bar: Int { case a }
struct X { var bar: Bar }

extension X: Codable {} // error

Oh... I misremembered. I'm sorry.... How can I delete this topic.

Terms of Service

Privacy Policy

Cookie Policy