Ios 为什么大多数在线代码示例在符合协议功能时使用override关键字?
目前,我使用的是Swift 5 XCode 12 我注意到,如果符合协议功能,则不需要关键字Ios 为什么大多数在线代码示例在符合协议功能时使用override关键字?,ios,swift,Ios,Swift,目前,我使用的是Swift 5 XCode 12 我注意到,如果符合协议功能,则不需要关键字override。比如说 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 然而,我看了很多在线示例代码。比如说, 我注意到他们中的许多人都在使用override关键字 如果我应用override关键字,我将得到错误 Method does not over
override
。比如说
func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
然而,我看了很多在线示例代码。比如说,
我注意到他们中的许多人都在使用override
关键字
如果我应用override
关键字,我将得到错误
Method does not override any method from its superclass
我可以知道为什么会这样吗?这是因为在线示例使用的是旧的XCode还是旧的Swift?如果示例使用的是的子类,则它们需要使用
override
关键字,因为UITableViewController
已经实现了UITableViewDelegate
和UITableViewDataSource
协议
class MyViewController: UITableViewController {
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
}
如果视图控制器是的子类,并且实现了UITableViewDelegate
和UITableViewDataSource
协议,则应删除override
关键字
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
}
您混淆了协议一致性(接口)和继承。
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
}