In Swift it’s kind of unsupported to implemented optional protocol methods.
You can, which is ugly, use the @objc syntax:
Sponsor Fastlane alternative - Codemagic CLI tools Are you tired of Ruby and Fastlane installation issues? There's got to be a better way! Discover Codemagic open source CLI tools. It is not a drop-in replacement for all of what Fastlane does (screenshots for example), but we use it at Codemagic to build and publish iOS and Android apps, also versioning and device provisioning. View on GitHub .
@ 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.
Keep your Swift knowledge current
Join 31,000+ developers receiving one practical Swift, SwiftUI, Xcode, and AI development update every Tuesday.
One practical email every Tuesday. Unsubscribe anytime.
Sponsor Fastlane alternative - Codemagic CLI tools Are you tired of Ruby and Fastlane installation issues? There's got to be a better way! Discover Codemagic open source CLI tools. It is not a drop-in replacement for all of what Fastlane does (screenshots for example), but we use it at Codemagic to build and publish iOS and Android apps, also versioning and device provisioning. View on GitHub . 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