Thwin Htoo Aung Thwin Htoo Aung - 1 year ago 88
iOS Question

initialization using ClassName.Type in Swift

In UIKit, if we use UITableView programmatically, we need to register UITableViewCell or our CustomCell.
Like ...

tableViewInstance.register(UITableViewCell.self, forCellReuseIdentifier: "blah blah");
// OR if we want to use our Custom Cell
tableViewInstance.register(CustomCell.self, forCellReuseIdentifier : "blah blah");

The point is, how does Apple Guys' UITableView know what type of cell we gave to register and how does it initialize the cell by our given type internally.

Any answer will be really appreciated. Thanks :)

Answer Source

UIKit is – as far as I know – still written in Objective-C, but even in Swift you can create an instance from class type, as in the following simplified example:

class MyTableView {

    var registrations: [String: UITableViewCell.Type] = [:]

    func register(theClass: UITableViewCell.Type, forCellReuseIdentifier identifier: String) {
        registrations[identifier] = theClass

    func dequeueCell(withIdentifier identifier: String) -> UITableViewCell {
        guard let theClass = registrations[identifier] else {
            fatalError("No class has been registered for \(identifier)")
        return theClass.init(style: .default, reuseIdentifier: identifier)

Here theClass has the type UITableViewCell.Type, and you can create an instance by calling the

init(style: UITableViewCellStyle, reuseIdentifier: String?)

method on it. For initialization from a "metatype value", the init method must be referenced explicitly, so

return theClass(style: .default, reuseIdentifier: identifier)

would not compile.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download