nyekimov nyekimov - 2 months ago 64
Swift Question

Swift 3 UITableView datasource method viewForHeaderInSection gives warning

After migration to Swift 3 I have the following method:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {}


And it gives me the warning


Instance method 'tableView(tableView:viewForHeaderInSection:)' nearly
matches optional requirement 'tableView(_:titleForHeaderInSection:)'
of protocol 'UITableViewDataSource'


Fix-it offers to make the method private or add @"nonobjc" annotation. How to resolve the warning?

Answer

I had similar warnings all over my app. There were 2 problems actually. I fixed all of the warnings either by adding the underscore to the method signature or by moving the method to the right extension which implements the protocol where the method comes from.

I think your problem might be the combination of both.

In more detail:

1) You might forget to add the "underscore" character before the "tableView:...", which makes it a different method in Swift 3 (in Swift 2.3 it doesn't matter). So you should change this:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

to this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

2) The method tableView(_:viewForHeaderInSection:) is from UITableViewDelegate protocol, but it looks like the compiler doesn't know about this method–it only knows of the methods from UITableViewDataSource and tries to advise you one of them (tableView(_:titleForHeaderInSection:)). So you either don't implement UITableViewDelegate at all or you do, but in another extension maybe?