为什么课程不必在原始中实现所有功能?
我是Swift的新鲜。 UitaiteViewDataSource和UitableViewDelegate具有许多功能。如果我有一个uiviewController可以采用它们,为什么不必须实现所有功能?在其他语言(例如Java)中,类必须实现接口中声明的所有功能。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为
uitaiteViewDataSource
和uitaiteViewDelegate
是Objective-C协议,而不是Swift协议。区别很重要,因为Objective-C协议允许您将某些方法标记为
可选
,这意味着它们不必由符合它们的人实现。该主题有一个旧但仍然有用的Apple Doc 在这里,但本质上是:(
从上面的链接中获取)
xyzpiechartviewDataSource
协议具有三种必需的方法。如果它们没有标记为@Optional
或@required
,则默认情况下需要它们。请注意,该属性是在级联级别应用的,直到找到另一个属性为止,因此两个- (nsString *)title forsementAtAtIndex :( nsuinteger)segmentIndex;
and andand
/代码>是可选的。- (bool)shosexplodesegrangegrentexAtAtex:(nsuinteger)sempementeger semmetIndex; <<<<
uitaiteViewDataSource
和uitableViewDelegate
您不需要实现的方法具有@Optional
属性。在Swift中,也可以具有具有可选实现的协议,但是您需要使用
@OBJC
属性将协议公开为C,并必须公开标记为可选的方法也是Objective-C。这就是xyzpiechartviewDataSource
在Swift中的样子:That's because
UITableViewDataSource
andUITableViewDelegate
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:
(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
andUITableViewDelegate
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 whatXYZPieChartViewDataSource
would look like in Swift:在文档中,您会注意到功能通常被标记为
可选
。例如; tableView(_:didSelectRowat声明意味着您不必实施它。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.