iOS

How does one declare optional methods in a Swift protocol?


As in most cases with Swift, you can’t actually declare optional methods in a protocol. However, the behaviors, which are optional in this case, can be implemented using protocol extensions in conjunction with default implementations. 

Here's how you can do it

Using Extensions:

  1. Define a Protocol: You just have to create your protocol with the methods you want.

  2. Use Protocol Extensions: The default implementation of all the methods in a protocol extension. By doing so, conforming types can decide to provide their own implementations if they wish to do so.

Here’s an example:

 

protocol MyProtocol {  func requiredMethod()  func optionalMethod() // This method will not be optional yet }  extension MyProtocol {  func optionalMethod() {  // Default implementation  print("Default optional method implementation")  } } class MyClass: MyProtocol {  func requiredMethod() {  print("Required method implementation")  }   // Uncommenting this will override the default optional method  // func optionalMethod() {  // print("Custom optional method implementation")  // } } let myClassInstance = MyClass() myClassInstance.requiredMethod() // Output: Required method implementation myClassInstance.optionalMethod() // Output: Default optional method implementation

 

 

 

Using Objective-C methods:

If you require optional methods, similar to those in Objective-C protocols, you can use @objc which shows your Swift protocol is compatible with Objective-C, and then declare methods as optional by using the @objc optional keyword. However, this means that for these new types, they have to be a subclass of NSObject. 

Here’s how it looks:

 

 

@objc protocol MyObjectiveCProtocol { func requiredMethod()  @objc optional func optionalMethod() // Optional method }  class MyObjCClass: NSObject, MyObjectiveCProtocol {  func requiredMethod() {  print("Required method implementation")  }  // optionalMethod can be implemented or omitted }  let myObjCInstance = MyObjCClass() myObjCInstance.requiredMethod() // Output: Required method implementation myObjCInstance.optionalMethod?() // Safe call; may or may not execute

 

Conclusion

When it comes to pure Swift protocols, all default implementations should be placed in extensions. In order to make methods optional for Objective-C compatibility use the @optional keyword.

 

Ready to transform your business with our technology solutions?     Contact Us today to Leverage Our iOS Expertise.

0

iOS

Related Center Of Excellence