Honey Honey - 29 days ago 7
iOS Question

Is there any reason Apple decided to use AnyClass rather than using UITableViewCell.Type?

With the code below, you could potentially pass

in for the

func register(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String)

and run into bugs.

However if it was written as:

func register(_ cellClass: UITableViewCell.Type?, forCellReuseIdentifier identifier: String)

Whatever passed has to be a subclass of
. It would no longer accept
. If passed it would throw an error at compile time, which is better.

So is there any reason why it's not written this way?

I'm not looking for opinions, just want to know would there be any downside if Apple wrote the way I suggested or are there any language limitations that I'm not aware of?

Answer Source

The API for UITableView comes from the Objective-C header file. The cellClass parameter in Objective-C is simply Class with the Swift equivalent being AnyClass. Unlike in Swift, Objective-C doesn't support declaring that the value of Class (AnyClass) be any specific type.

So when this API is translated for Swift, you are left with the generic AnyClass in Swift.

It is odd that the documentation doesn't specify that the passed in class/type should be UITableViewCell (or a subclass).

This limitation in Objective-C is discussed (thanks Larme) here: Specific Class type parameter in Objective-C