Possible to add typealias for section of code?

Viewed 106

In my view controller, I'm reloading tableView in multiple places using below code.

DispatchQueue.main.async { self.tableView.reloadData() }

Looks like I'm re-writing the same code in multiple places. Is it possible to write typealias for this. I know this can be written in a common method and just call it wherever required. Just curious, any alternative ways ??

2 Answers

It's not a “type”, so a typealias doesn't make sense. Writing a function for it does. Or define a code snippet so you can write accelerate the insertion of this common code snippet with just a few keystrokes.

E.g. select the code, right click on it, and chose “Create Code Snippet”:

enter image description here

You can supply a “completion” string, if you want, e.g. tvrd in this example:

enter image description here

Then you can just type your auto completion string and your code snippet will be inserted:

enter image description here

As mention in @Rob answer is the correct and good answer. If you are working on UIViewController subclass and have a TableView controller, You can use this extension. This will help you with all the view controllers.

extension UITableView {
    func reloadOnMainIfNeeded() {
        if Thread.isMainThread {
            self.reloadData()
        } else {
            DispatchQueue.main.async {
                self.reloadData()
            }
        }
    }
}

Usage

class TestController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.reloadOnMainIfNeeded()
    }
}

class TestTableController: UITableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.reloadOnMainIfNeeded()
    }
}
Related