Swift 5.6: Optional Protocol Requirements

Andreea Andro
2 min readJul 1, 2022

You can define optional requirements for protocols. These requirements don’t have to be implemented by types that conform to the protocol.

Optional requirements are prefixed by the optional modifier as part of the protocol’s definition.

Their scope: to allow writing code that interoperates with Objective-C. Both the protocol and the optional requirement must be marked with the @objc attribute. Note that @objc protocols can be adopted only by classes that inherit from Objective-C classes or other @objc classes. They can’t be adopted by structures or enumerations.

The following example defines an integer-counting class called Counter, which uses an external data source to provide its increment amount. This data source is defined by the CounterDataSource protocol, which has two optional requirements:

@objc protocol CounterDataSource {
@objc optional func increment(forCount count: Int) -> Int
@objc optional var fixedIncrement: Int { get }
}

Strictly speaking, you can write a custom class that conforms to CounterDataSource without implementing either protocol requirement. They’re both optional, after all. Although technically allowed, this wouldn’t make for a very good data source.

class Counter {
var count = 0
var dataSource: CounterDataSource?
func increment() {
if let amount = dataSource?.increment?(forCount: count) { count += amount} else if let amount = dataSource?.fixedIncrement { count += amount}
}
}

One datasource class implementing only the property requirement:
class ThreeSource: NSObject, CounterDataSource {
let fixedIncrement = 3
}

One datasource class implementing only the method requirement:
class TowardsZeroSource: NSObject, CounterDataSource {
func increment(forCount count: Int) -> Int {
if count == 0 { return 0}
else if count < 0 { return 1}
else { return -1 }
}
}

Would you use Optional Protocol Requirements?

Excerpts From
The Swift Programming Language (Swift 5.6)
Apple Inc.
https://books.apple.com/ro/book/the-swift-programming-language-swift-5-6/id881256329
This material may be protected by copyright.

--

--