Protocols and Extensions

Since protocols in Swift are implemented directly in the class/struct, during definition or via extension, the protocol implementation ends up changing the class/struct globally. To see the problem with this, imagine that you have two different libraries relying on different JSON protocols:

 protocol JSONA {
  func toJSON(precision: Integer) -> String
 }
 protocol JSONB {
  func toJSON(scale: Integer) -> String
 }

If the preceding protocols have different specifications on how the precision argument must be handled, we will be able to implement only one of the two previous protocols. That’s because implementing any of the protocols above means adding a toJSON(Integer) method to the class/struct, and there can be only ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.