- Swift 4 Protocol-Oriented Programming(Third Edition)
- Jon Hoffman
- 128字
- 2021-07-08 09:42:35
Optional requirements
There are times when we want protocols to define optional requirements. An optional requirement is a method or property that is not required to be implemented. To use optional requirements, we need to start off by marking the protocol with the @objc attribute.
It is important to note that only classes can adopt protocols that use the @objc attribute. Structures and enumerations cannot adopt these protocols.
To mark a property or method as optional, we use the optional keyword. The following example shows how we would create both an optional property and also an optional method:
@objc protocol Phone { var phoneNumber: String {get set} @objc optional var emailAddress: String {get set} func dialNumber() @objc optional func getEmail() }
Now let's explore how protocol inheritance works.