0

I'm kind of stuck trying to understand .self in swift, always I register a custom cell in an collectionView or an tableView I have to register like customCollectionViewCell.self but why not for example customCollectionViewCell() ?

I've tried in the playground to type String.self in a var to see what happens and it give me no errors but when I try to give it a value it give me the following error

Cannot assign value of type 'String' to type String.Type

what does it mean?

mfaani
  • 33,269
  • 19
  • 164
  • 293
Lucas
  • 746
  • 8
  • 23
  • you register the `Class` with .self. You would be creating an instance with customCollectionViewCell(). – meggar Oct 01 '18 at 15:10
  • 2
    `String.self` refers to the *Type* **String**. `String()` is an *Instance* of the **String** class – Sander Saelmans Oct 01 '18 at 15:10
  • See [here](https://stackoverflow.com/a/41709040/5175709) and also there is a reason for why we're passing a _Type_ rather than an object itself. You normally pass types to functions where it's not needed for you to instantiate that object yourself rather that function will instantiate the object for you! – mfaani Oct 01 '18 at 17:52

1 Answers1

5

Type() is shorthand notation for Type.init(), so String() calls String.init() and hence initialises a String.

On the other hand, String.self returns the meta type of String, which is a type that represents the String type itself rather than any instance of that type. For more information on meta types, see the Metatype Type section of the official Swift language reference.

In your specific example, you need to register a UITableViewCell subclass type rather than an instance of a specific type, hence you need to use YourCellType.self.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 1
    The answer would be more complete if you also explain or add a link as to **why** we're passing the _type_ for dequeueing purposes – mfaani Oct 01 '18 at 17:03