There are @optional keywords in protocol in Objective-c, and the method that is modified by this keyword is not required to be implemented. We can define a series of methods through an interface, and then selectively implement several of these methods by implementing the class of the interface. In many cases the interface method is optional in the Cocoa API, and all methods of protocol in Swift must be implemented completely differently.
Methods that do not work properly if they are not implemented are generally necessary, whereas methods that are relatively similar to event notifications or configuration of non-critical properties are generally optional. The best example I think is Uitableviewdatasource and uitableviewdelegate. There are two necessary methods in the former:
Swift Code
- -tableview:numberofrowsinsection:
- -tableview:cellforrowatindexpath:
It is used to calculate and prepare the height of the tableview and to provide the style of each cell, while the other methods that return the number of sections or whether the cell can be edited have default behavior, which are optional methods All the methods in the latter (uitableviewdelegate) are detailed configuration and event callbacks, so all are optional.
There are no options available in the native Swift protocol, and all defined methods must be implemented. If we want to define an optional interface method as in objective-c, we need to define the interface itself as OBJECTIVE-C, which is to add @objc before the protocol definition. In addition, unlike @optional in objective-c, we use the keyword optional without the @ symbol to define an optional method:
Swift Code
- @objc protocol Optionalprotocol {
- Optional func Optionalmethod ()
- }
In addition, for all declarations, their prefix decorations are completely separate. Which means you can't use a @optional like you did in objective-c. Specifies that the next few methods are optional, that each optional method must be prefixed, and that, for methods that do not have a prefix, they must be implemented by default:
Swift Code < param name= "Quality" value= "High" >
- @objc protocol Optionalprotocol {
- Optional func Optionalmethod ()//optional
- Func Necessarymethod ()//Must
- Optional func Anotheroptionalmethod ()//optional
- }
An unavoidable limitation is that the @objc-modified protocol can only be implemented by class, that is, for struct and enum types, we cannot have an optional method or attribute in the interface that they implement.
In swift, how can I define an optional interface like objective-c?