In Swift it’s kind of unsupported to implemented optional protocol methods.
You can, which is ugly, use the @objc
syntax:
Capture, Debug, and Optimize Your HTTP(s) Traffic in One AppNeed to capture your HTTPS network? Try Proxyman! 1 click to work with iOS Simulator, Android Emulators, and other devices. Get started.
@objc protocol MyProtocol {
optional func doSomething();
}
class MyClass : MyProtocol {
// no error
}
Another disadvantage here is that structs are unsupported, as you’re bridging for Objc.
Simple Tools for Network DebuggingProxyman is a best-in-class native macOS app that lets developers capture, decrypt, and manipulate HTTP(s) requests and responses with ease. Trusted by over 250,000 developers worldwide, it provides powerful debugging tools—from breakpoints to local mapping—ensuring you spend less time troubleshooting and more time building great software. Get started.
Using protocol extensions to create optional protocol methods
However, with Swift 2.0 it’s possible to define protocol extension. This allows you to create optional methods for your protocol easily:
protocol MyProtocol {
func doSomethingNonOptionalMethod()
func doSomethingOptionalMethod()
}
extension MyProtocol {
func doSomethingOptionalMethod(){
// leaving this empty
}
}
As stated in this thread, many people are asking this feature:
http://stackoverflow.com/questions/24032754/how-to-define-optional-methods-in-swift-protocol