Using @objc in swift, we can create an optional methods inside protocol like
@objc protocol MyProtocol {
@objc optional func anOptionalMethod()
}
But how to create an optional protocol methods without using @objc ?
Using @objc in swift, we can create an optional methods inside protocol like
@objc protocol MyProtocol {
@objc optional func anOptionalMethod()
}
But how to create an optional protocol methods without using @objc ?
You can define default func implementation by:
protocol Opt {
func requiredFunc()
func optionalFunc()
}
extension Opt {
func optionalFunc() {}
}
With this you don't have to implement optionalFunc() in classes conforming to Opt, because they already have their default implementation.
Let's create an optional protocol methods using extension of that protocol and use it:
//: Playground - noun: a place where people can play
import UIKit
protocol someProtocol {
func a()
func b()
}
extension someProtocol {
func c() {
print("This is optional protocol method")
}
var someProperty: String {
return "some optional computed property"
}
}
class A: someProtocol {
func a() {
print("a")
}
func b() {
print("b")
}
// It's upto you to implement c() functionality,
// this is an optional protocol method
func c() {
print("I am overriding C functionality")
}
}
let obj = A()
obj.a()
obj.b()
obj.c()
print(obj.someProperty)
a
b
I am overriding C functionality
some optional computed property
Swift protocols do not support optional methods.
Apple Docs:
Optional Protocol Requirements
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. Optional requirements are available so that you can write 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.
One common use for optional methods in protocols is to define optional callbacks a delegate can listen for. This scenario is best achieved using the protocol
+ extension
approach (to provide do-nothing default implementations for tall of the optional methods).
For some other cases, it may be more appropriate to use multiple protocols:
protocol Storage {
func read() -> Data
}
protocol MutableStorage: Storage {
func write(data: Data
}
The standard library uses this approach for Sequence
, Collection
, and friends.