Swift Protocols and Opaque Return Types
Explore Swift protocols to understand how they define required properties and methods for class conformance. Learn about opaque return types using the some keyword to return any type conforming to a protocol. This lesson helps you grasp key concepts for building flexible, maintainable Swift code and working with Apple frameworks.
We'll cover the following...
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 ...