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?
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.
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With