Optional methods in protocols

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

In Swift, If you conform to a protocol you need to implement all its methods or properties. Optional methods are not allowed when implementing protocols. For instance:

protocol ImageDownloadable {
    func downloadDidStart()
    func downloadDidEnd()
    func downloadDidStop()
    func progressBarShouldStartMoving() -> Bool
    func progressBarDidFinishMoving() -> Bool
    func progressBarShouldHidden() -> Bool
}

We can try some tricks to make the optional methods.

  • Use default implementation using the extension.
  • Splitting the protocols with many protocols and conform only necessary one. You can use typealias(How and when to use typealias in Swift?) to merge protocols.
  • Using the @objc attribute on a Swift protocol. It provides the opportunity to mark methods as being optional. In this case, you can not use structs, enums and protocol extensions with that protocol.
// First scenario
protocol ImageDownloadable {
    func downloadDidStart()
    func downloadDidEnd()
    func downloadDidStop()
    func progressBarShouldStartMoving() -> Bool
    func progressBarDidFinishMoving() -> Bool
    func progressBarShouldHidden() -> Bool
}

extension ImageDownloadable {
    func downloadDidEnd() {
      ...
    }
}

// downloadDidEnd is optional


// Second scenario
protocol ImageDownloadStatusProviding {
    func engineDidStart()
    func engineWillStop()
    func engineDidStop()
}

protocol ProgressBarStatusProviding {
    func progressBarShouldStartMoving() -> Bool
    func progressBarDidFinishMoving() -> Bool
    func progressBarShouldHidden() -> Bool
}


// Third scenario
@objc protocol ImageDownloadable {
    // Optional
    @objc func downloadDidStart()
    @objc func downloadDidEnd()
    @objc func downloadDidStop()
    // Non-optional
    func progressBarShouldStartMoving() -> Bool
    func progressBarDidFinishMoving() -> Bool
    func progressBarShouldHidden() -> Bool
}


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.