8

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 ,?

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256

4 Answers4

14

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
4

Encoding The process of converting your custom type instances to other representation such as JSON and pList is known as Encoding or Serialization. For encoding, custom types conform to Encodable protocol.

Decoding The process of converting data in representation such as JSON or pList to instance of your custom type is known as Decoding or Deserialization. For decoding, custom types conform to Decodable protocol.

Codable To support both encoding and decoding, custom types can conform to Codable protocol which conforms to both Encodable and Decodable.

to Read more about Codable, Decoding and Encoding Click on the this Link

iFateh
  • 570
  • 2
  • 6
  • 22
3

Don't think so. Codable means they can be decoded from and encoded into another representation. Decodable means it can be decoded, but not encoded. And encodable is the opposite of that.

Thijs van der Heijden
  • 1,147
  • 1
  • 10
  • 25
3

They are functionally the same but you can do things with the & syntax that you can't with a comma separated list. Neither of these would work with the comma approach.

public typealias Codable = Decodable & Encodable

func doSomething(with item: ProtocolA & ProtocolB) {
}
Rob C
  • 4,877
  • 1
  • 11
  • 24