How to declare optional methods in a Swift protocol?
Hello! I started learning Swift and am trying to understand protocols. I have a `MyDelegate` protocol that I want to use for delegation. I want some methods in this protocol to be optional — meaning the class that adopts the protocol can choose not to implement them.
Here's what I'm trying to do:
```swift
protocol MyDelegate {
func requiredMethod()
optional func optionalMethod() // Error: 'optional' can only be applied to members of an @objc protocol
}
```
The compiler gives an error. I read that in Objective-C you could mark methods as `@optional`, but in Swift this doesn't work directly. I also tried using protocol extensions, but I'm not sure if I'm doing it correctly.
My goal is to create a protocol where one method is required (the
No answers yet.
Log in to leave an answer
Blogs
Asynchronous Programming in JavaScript: A Complete Guide for Node.js
Java Application Performance Optimization: Best Practices and Tools
Code Coverage in Swift: How to Measure and Improve Quality
Chaos Engineering for C++: How to Harden Your Software