viewForHeaderInSection - What to return for no header?

If you use this way you don't need to calculate the height.

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 50

If you have empty sections you can set the height to zero or you don't need this method.

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 {
            return 0
        }
        return UITableView.automaticDimension
    }

Whenever you implement the viewForHeaderInSection method you must also implement the heightForHeaderInSection method. Be sure to return 0 for the height for sections that have no header.