Swift Protocols and Opaque Return Types

Learn what Swift protocols are, how to write your own and how to make a class comply with one. Also, explore opaque return types, find out how they relate to protocols, and how to use them.

Understanding Swift protocols

By default, there are no specific rules to which a Swift class must conform as long as the class is syntactically correct. In some situations, however, a class will need to meet certain criteria to work with other classes. This is particularly common when writing classes that need to work with the various frameworks that comprise the iOS SDK. A set of rules that define the minimum requirements, which a class must meet, is referred to as a Protocol. A protocol is declared using the protocol keyword and simply defines the methods and properties that a class must contain to be in conformance. When a class adopts a protocol but does not meet all of the protocol requirements, errors will be reported stating that the class fails to conform to the protocol.

Consider the following protocol declaration. Any classes that adopt this protocol must include both a readable String value called name and a method named buildMessage(), which does not accept parameters and returns a String value:

protocol MessageBuilder {
 
    var name: String { get }
    func buildMessage() -> String
}

Below, a class has been declared which adopts the MessageBuilder protocol but fails to compile:

Get hands-on with 1200+ tech skills courses.