Sobes.tech
Junior — Middle

Is it possible to define a function as an optional part of a protocol interface?

sobes.tech AI

Answer from AI

In Swift, protocol methods can be marked as optional, but only if the protocol is marked with @objc and inherits from NSObjectProtocol. This is because optional methods are only supported in protocols compatible with Objective-C. The @objc optional keyword is used for this purpose.

Example:

@objc protocol MyProtocol {
    @objc optional func optionalMethod()
    func requiredMethod()
}

If the protocol does not inherit from NSObjectProtocol or is not marked with @objc, then all methods must be implemented obligatorily.

Is it possible to define a function as an optional… - sobes.tech