2

I am trying to define a identifier (class name) static computed variable on a UITableViewCell extension and access the identifier by sending a subclass to a generic function.

When accessing the Subclass.identifier, I get the name of the subclass, but when accessing it from a generic function, it returns UITableViewCell

code:

protocol Identifiable {
    static var identifier: String { get }
}

extension Identifiable {
    static var identifier: String { return String(describing: Self.self) }
}

extension UITableViewCell: Identifiable { }

class Subclass: UITableViewCell {

}

print("\(Subclass.identifier)") // Output: "Subclass"

func blah<T: Identifiable>(_ cellType: T.Type) {
    print("\(cellType.identifier)")
}
blah(Subclass.self) // Output: "UITableViewCell"

How can I get the Subclass identifier in the generic function without having to conform to the Identifiable protocol on all of my UITableView subclasses?

  • Related: [Why do Self and self sometimes refer to different types in static functions?](http://stackoverflow.com/questions/42037852/why-do-self-and-self-sometimes-refer-to-different-types-in-static-functions). The behaviour you're seeing is the "existential when the method is a protocol requirement" behaviour. Due to the sheer complexity of factors that determine the value of `Self`, `self` is nearly always preferred. – Hamish Mar 16 '17 at 16:36

1 Answers1

2

You have an unnecessary Self. You want:

extension Identifiable {
    static var identifier: String { return String(describing: self) }
}

When you say Self.self you are saying "This class's self" and "This class" is the the thing that you have extended (being UITableViewCell). When you just say self you are saying "this thing" where "this thing" is the thing that is executing the function, so Subclass

Paulw11
  • 108,386
  • 14
  • 159
  • 186