I was playing with Swift 4 and Codable
a little bit and got stucked with some scenario having nested protocols which all conform to Codable
.
Simplified example looks like this:
protocol CodableSomething: Codable {}
protocol CodableAnotherThing: Codable {
var something: CodableSomething { get }
}
struct Model: CodableAnotherThing {
var something: CodableSomething
}
This code is making a build errors with Xcode 9 Beta 5:
Now, I wasn't expecting these errors as I understood that conformance to these protocols will be auto-generated by the compiler, when in fact, I couldn't even implement this conformance manually without having build errors. I've also tried several different approaches to solve this kind of a nested model structure with using Codable
but I just couldn't make it work.
My question: Is this a compiler bug (it's still beta) or I'm doing something wrong?
Codable is the combined protocol of Swift's Decodable and Encodable protocols. Together they provide standard methods of decoding data for custom types and encoding data to be saved or transferred.
Codable is a protocol that a type can conform to, to declare that it can be encoded and decoded. It's basically an alias for the Encodable and Decodable protocols. typealias Codable = Encodable & Decodable.
A lot of Swift's built-in types already conform to Codable by default. For example, Int , String , and Bool are Codable out of the box. Even dictionaries and arrays are Codable by default as long as the objects that you store in them conform to Codable .
If you switch protocol
CodableSomething
To a struct you would have no errors,
take it further and read more about Codable
what are the types that a Codable can work on and why ? up there you are basically saying this to xCode
struct foo: Codable {
var ok: Codable
}
That is not right take a deep look at it,
Codable
is a Typealias
you need to conform to to use its subs such as .Decode()
, .Encode()
those methods works with values not abstraction types
so giving a Codable
Type to a Variable thats not going to work out.
because Codable
is a typealias
that indicates
Decodable
& Encodable
/// A type that can convert itself into and out of an external representation.
public typealias Codable = Decodable & Encodable
and both of Decodable and Encodable are Protocols that make sure those values are encodable and decodable.
so Codable is an abstraction it can't Decode or Encode Variables of it self Type but can encode and decode Types that are confirmed to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With