Why is it when I set UITableViewController navigationItem.searchController with UISearchController, navigation.searchController still is nil?

For some reason, when I set UITableViewController navigationItem.searchController with a UISearchController, it doesn't take it.

Here is my code:

let searchController = UISearchController(searchResultsController: nil)

if #available(iOS 11.0, *) {

    print("?", navigationItem.searchController)
    print("!", searchController)
    navigationItem.searchController? = searchController
    print("?", navigationItem.searchController)

} else {

    tableView.tableHeaderView = searchController.searchBar
}

Here is the debug window:

? nil
! <UISearchController: 0x105077600>
? nil
Accepted Answer

Why ?

    navigationItem.searchController? = searchController

and not

    navigationItem.searchController = searchController

This is a general rule for optional, not specific to searchController of course.

This is illustrated by the following code:

var i : Int?
i? = 2
print("i is", i)
i = 4
print("i is", i)

Which yields:

  • i is nil
  • i is Optional(4)
Why is it when I set UITableViewController navigationItem.searchController with UISearchController, navigation.searchController still is nil?
 
 
Q