Swift - Clear TableView

This post was a long time ago, but for anyone interested, here is what I use in my app.

If you really want to use the deleteRows function (for animation purposes for instance), then you can do the following:

let count = self.tableView(self.tableView, numberOfRowsInSection: 0)
// insert action that deletes all your data from the model here
// e.g. self.arrayOfRows = []
self.tableView.deleteRows(at: (0..<count).map({ (i) in IndexPath(row: i, section: 0)}), with: .automatic)

What it basically does is convert the range 0..<count to [IndexPath] values and instructs the table view to delete those paths, using the deleteRows method.


Don't use an optional type.
Declare an non-optional empty array.

var searchResults : [[String : Any]]()

then numberOfRowsInSection can be just

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchResults.count
}

To clear the table view write

searchResults.removeAll()
tableView.reloadData()

No unwrapping, no checking for nil, no problems.

Tags:

Swift2