The Case for Protocols

Protocols are a fantastic feature in Swift. Per the documentation, “a protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”

Let’s see their example:

 protocol FullyNamed {
  var fullName: String { get }
 }
 struct Person: FullyNamed {
  var fullName: String
 }
 let john = Person(fullName: "John Appleseed")
 // john.fullName is "John Appleseed"

In the preceding example, we defined a FullyNamed protocol and implemented it while defining the Person struct. The benefit of protocols is that the compiler can now guarantee the struct complies with the definitions specified in the protocol. In case the protocol changes in the future, you’ll find ...

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.