Adding name property to Metatype

(Kiel Gillard) #1

Is this a dumb idea?

let metatype = type(of: SomeClass.self)
let name: String = metatype.name
print(name) // "SomeClass"

A common pattern in iOS is to use the name of a type as the identifier for reusable cells. Here's how people on StackOverflow recommend or endorse getting names of types.

What'd the difficultly be implementing this (presumably) in the compiler?

Thoughts?

Kiel

(Adrian Zubarev) #2

You can imagine that every type in Swift has a nested type called Type.

class A {
  static var name = "A"
  // reserved by compiler
  metatype Type {
    var name = "A"
  }
}

Static members of your type are instance members of the its own metatype. This is why I think we cannot burn name as a static citizen for every type.

If you write A.name you basically fetching the metatype implicitly by calling A.self and accessing its instance member name. A.name is the same as if you‘d write A.self.name.

However you can make use of String(describing: metatype).

// this does the trick for me
extension UITableViewCell {
  static var identifier: String {
    return String(describing: self)
  }
}
(Martin R) #3

As I understand it from Getting the (more) fully qualified name of a type, it is not guaranteed that this gives the (unqualified) type name. This is also discussed in Relying on String(describing:) to get the name of a type

1 Like
(Stern) #5

I use String(describing:) for this purpose. It did seem from the description of that method that it wasn't truly guaranteed to return the class name but it does seem to work. There are a handful of other ways to get the class name but none seem as terse as String(describing:) Needless to say there should be a terse way to get a class name that is guaranteed to work.