Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a protocol with methods that are optional?

I noticed methods marked optional in several protocols defined in the iPhone SDK, such as the UIActionSheetDelegate protocol for example.

How can I define a protocol of my own, and set a few of the methods as optional?

like image 469
jpm Avatar asked Nov 26 '08 23:11

jpm


People also ask

How do you create optional methods in Protocols?

Swift protocols on their side do not allow optional methods. But if you are making an app for macOS, iOS, tvOS or watchOS you can add the @objc keyword at the beginning of the implementation of your protocol and add @objc follow by optional keyword before each methods you want to be optional.

What is optional func in Swift?

For pure Swift code, you can instead use a property whose type is the same as the type of the function you want be optional (but wrapped into an Optional ), and assign it to nil in implementing types that you don't want to implement that function (unfortunately, you won't have named arguments and generics).

How is optional implemented in Swift?

Implementing Integer optionals in Swift So optionals can be implemented through an enum (with associated value). Calling it “Optional” when there is no value is not ideal, but matches the internal implementation.

What is protocol method?

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.


1 Answers

From the Apple page on "Formal Protocols":

Optional Protocol methods can be marked as optional using the @optional keyword. Corresponding to the @optional modal keyword, there is a @required keyword to formally denote the semantics of the default behavior. You can use @optional and @required to partition your protocol into sections as you see fit. If you do not specify any keyword, the default is @required.

@protocol MyProtocol

- (void)requiredMethod;

@optional
- (void)anOptionalMethod;
- (void)anotherOptionalMethod;

@required
- (void)anotherRequiredMethod;

@end
like image 125
Matt Gallagher Avatar answered Oct 04 '22 08:10

Matt Gallagher