Swift For Dummies
Book image
Explore Book Buy On Amazon

A protocol is introduced in Swift by the keyword protocol. It contains the ­declarations that must be implemented by the types that adopt the protocol. The most common elements of a protocol are methods and properties. The example shown here uses a single property, but multiple properties in a ­protocol are permitted. You can also have properties in protocols that are adopted by classes and structures.

Functions (methods) can be adopted by all the types that can adopt protocols (that is, by classes, structures, and ­enumerations).

A protocol is named just as other Swift elements are named. The basic protocol declaration looks like this:

protocol MyProtocol {
}

As with classes, structures, and enumerations, the name is capitalized. In fact, most Swift objects except for properties and functions are capitalized, and they use internal camelCase (capital letters for each of the embedded words except the first).

If the protocol contains a function that must be implemented by types that adopt it, the protocol declaration might look like this:

protocol MyProtocol {
  func myFunc () -> String
}

An object conforming to MyProtocol must implement myFunc.

In order to focus on the syntax of protocols, the examples here show instance methods rather than type methods, which are comparable to class methods in Objective‐C. Instance methods are most commonly used.

Protocols can inherit from one another. Thus, you can declare a pair of protocols as follows:

protocol MyProtocol {
  func myFunc () -> String
}
protocol MyProtocol2: MyProtocol {
  func myFunc2 () -> String
}

An object conforming to MyProtocol must implement myFunc. An object conforming to MyProtocol2 must implement myFunc2, but it must also implement myFunc because MyProtocol2 inherits from MyProtocol. If MyProtocol2 stands on its own (that is, if it does not inherit from MyProtocol), objects that conform to either MyProtocol or MyProtocol2 must implement myFunc — but this is the same function in both protocols. This is okay. Just don’t think you’d have to implement it twice.

Don’t use a structure in which an identically‐named function (or property) is used in multiple protocols unless you really mean it. (An init function would be a good example of the proper use of duplicate function names.)

If you want your protocol to be adopted only by classes, use the keyword class in the list, as in the following:

Protocol MyProtocol: class, MyProtocolToInheritFrom

Note that the class is the keyword you use: It’s not the name of a class.

About This Article

This article is from the book:

About the book author:

Jesse Feiler is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast’s The Roundtable.

This article can be found in the category: