tadija
tadija

Reputation: 3261

Nested Codable protocols with Swift 4

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?

Upvotes: 7

Views: 2104

Answers (1)

Mohmmad S
Mohmmad S

Reputation: 5088

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.

Upvotes: 4

Related Questions