Search code examples
swiftcompositioncodabledecodableencodable

Swift Encodable, Decodable Vs Codable


Found in Apple doc, that Codable protocol is composed of Encodable and Decodable. Thus,

Codable = Encodable & Decodable

Now, let's say I implemented below classes,

class X: Codable {
    var name: String
}

class Y: Encodable, Decodable {
    var name: String
}

class Z: Encodable & Decodable {
    var name: String
}

So, is there any functional difference among the classes, X, Y and Z?

If there is no deference why can't we use & in the places of ,?


Solution

  • No there isn't any difference , Codable is a typealias for Encodable & Decodable , so it combines the 2 protocols you're free to use any way

    In Swift & is the same as , in protocol composition so Encodable, Decodable = Encodable & Decodable = Codable