I'm a newer to Swift. UITableViewDataSource and UITableViewDelegate have so many functions. If I have a UIViewController to adopt them, why don't I have to implement all the functions? In other languages such as Java, the class has to implement all the functions declared in the interface.
CodePudding user response:
That's because UITableViewDataSource
and UITableViewDelegate
are Objective-C protocols, not Swift protocols.
The distinction is important, because Objective-C protocols allow you to mark some methods as optional
, meaning they do not have to be implemented by whoever conforms to them.
There is an old but still useful Apple doc on the topic here, but essentially:
@protocol XYZPieChartViewDataSource
- (NSUInteger)numberOfSegments;
- (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
@optional
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
- (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex;
@required
- (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex;
@end
(Taken from the link above)
The XYZPieChartViewDataSource
protocol has three required methods. If they are not marked as either @optional
or @required
, they are required by default. Note that the attribute is applied in cascade until finding another attribute, so both - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
and - (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex;
are optional.
The methods of UITableViewDataSource
and UITableViewDelegate
that you are not required to implement have the @optional
attribute.
In Swift, it is possible to have protocols with optional implementations as well, but you need to expose your protocol to Objective-C with the @objc
attribute, and the methods that are marked as optional must be exposed to Objective-C as well. This is what XYZPieChartViewDataSource
would look like in Swift:
@objc protocol XYZPieChartViewDataSource {
@objc func numberOfSegments() -> Int
@objc func sizeOfSegmentAtIndex(_ segmentIndex: Int) -> CGFloat
@objc optional func titleForSegmentAtIndex(_ segmentIndex: Int) -> String
@objc optional func shouldExplodeSegmentAtIndex(_ segmentIndex: Int) -> Bool
@objc func colorForSegmentAtIndex(_ segmentIndex: Int) -> UIColor
}
CodePudding user response:
In the documentation you'll notice the functions are often marked as optional
. For example; tableView(_:didSelectRowAt:) has "optional" before the method declaration meaning you do not have to implement it.