DEV Community

Cover image for Optional function in swift Protocol
NalineeR
NalineeR

Posted on

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.

Top comments (0)