Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 13, 2023 09:51 am GMT

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{}

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() {    }}

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(){    }}

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()}

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.


Original Link: https://dev.to/nalineer/optional-function-in-swift-protocol-442j

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To