64

Right now I'm using NSClassFromString, but is there a better way to get an AnyClass! from a class in Swift? I am trying to pass the reference to my collection view's -registerClass:forCellWithReuseIdentifier: method.

collectionView.registerClass(NSClassFromString("MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")
Enrique Bermúdez
  • 1,740
  • 2
  • 11
  • 25
jarjar
  • 1,681
  • 2
  • 15
  • 19

4 Answers4

154

This is currently just a blind but educated guess, but using Class.self might be what you want.

collectionView.registerClass(MyCoolViewCell.self, forCellWithReuseIdentifier: "MyCoolViewCell")
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
  • 5
    This is really bad syntax, but is seems to work. Thanks! – dasdom Jun 21 '14 at 16:47
  • 12
    Bad syntax? `.self` is very concise. – Matthew Quiros Aug 27 '14 at 08:13
  • 4
    `self` in most languages (similar to `this`) almost always refers to an instance of the class, I think that's why a having `ClassName.self` refer to the Class type is confusing. – Zorayr May 10 '15 at 20:03
  • I'm sorry, but the difference between self as a keyword and .self as a method name seems pretty clear to me. One is a keyword, the other is a method. Keywords should NOT automatically preclude the use of a method or property name matching them, though I will concede it's usually a good idea to avoid using them for clarities sake. (It's important for the rare occasion when NOT using them is even more unclear, generally because you've been forced to use the thesaurus) – RonLugge May 29 '15 at 19:54
  • 2
    I am an Objective-C developer and I find this confusing but it works! – user3378170 Jun 04 '15 at 08:50
  • Objective-C has the same syntax, `UIButton.self` is equivalent to `UIButton.class`. – DawnSong Mar 13 '16 at 01:49
  • 2
    I find `UIButton.class` much more adequate than `UIButton.self`, pity they dropped this syntax from Swift. – Zoltán Mar 24 '16 at 11:09
22

In case you are using a nib file, use this code instead:

    let nib = UINib(nibName: "MyCoolViewCell", bundle: nil)
    collectionView?.register(nib, forCellWithReuseIdentifier: "MyCoolViewCellIdentifier")
atulkhatri
  • 10,896
  • 3
  • 53
  • 89
15

In Swift 3:

self.collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "CustomCollectionViewCellReuseIdentifier")
lostAtSeaJoshua
  • 1,695
  • 2
  • 21
  • 34
Maria Ortega
  • 371
  • 4
  • 8
0

NSClassFromString("MyCoolViewCell")might get nil.
Should add module name in prefix:
collectionView.registerClass(NSClassFromString("MyApp.MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")

If cellClass not a variable, use MyCoolViewCell.self is a better choice.

yhlin
  • 189
  • 2
  • 9