O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required