DEV Community

Cover image for Optional function in swift Protocol
NalineeR
NalineeR

Posted on

3 1

Optional function in swift Protocol

In this article we will check how to make the protocol functions optional for implementation.

Let's create a protocol named Eatable and make our VegetableVC class conform to this.

protocol Eatable{
    func addItem()
}

class VegetableVC:Eatable{

}
Enter fullscreen mode Exit fullscreen mode

You will get an error if you run with this code. Because the functions in protocol are of Required type by default i.e. whoever conforms to this will have to implement this.

Image description

So let's add the functions to remove this error.

class VegetableVC:Eatable{
    func add() {

    }
}
Enter fullscreen mode Exit fullscreen mode

But what if we want to add a function which is optional to implement? Let's check how to do it -

First lets add a new function as follow - func delete()

Now we have 2 approaches to achieve the optional implementation -

1. using extension - In this we extend the protocol and provide a default implementation.

extension Eatable{
    func delete(){

    }
}
Enter fullscreen mode Exit fullscreen mode

If you run the code now you see you don't get error even though VegetableVC class has not implemented the delete() method.

2. using optional keyword - In this approach we mark the function as optional using the keyword.

@objc protocol Eatable{
    func add()
    @objc optional func delete()
}
Enter fullscreen mode Exit fullscreen mode

You can see we have marked protocol and func with @objc becuase 'optional' can only be applied to members of an @objc protocol.

Delete the extension we added previously and run the program.
It runs without any error.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay