1

If I define a UICollectionViewCell subclass:

class TestCell<T>: UICollectionViewCell {
  var float: CGFloat? = 3
  var string = "abc"
}

Register it:

collectionView.registerClass(TestCell<String>.self, forCellWithReuseIdentifier: "Test")

Then use it:

collectionView.dequeueReusableCellWithReuseIdentifier("Test", forIndexPath: indexPath) as! TestCell<String>

I notice strange behavior with the properties that should have been initialized.

  • float == Optional(0.0)
  • string == ""

Why is this happening and how can I fix it?

This is on Xcode 7.3

Senseful
  • 73,679
  • 56
  • 267
  • 405

1 Answers1

1

Looks like this was a bug related to generics.

If you get rid of the generic specifier, the variables are initialized as you expect.

If you need the generic specifier, you can workaround the issue by instantiating the properties in the init method rather than inline:

class TestCell<T>: UICollectionViewCell {
  override init(frame: CGRect) {
    float = 3
    string = "abc"
    super.init(frame: frame)
  }

  var float: CGFloat?
  var string: String
}
Senseful
  • 73,679
  • 56
  • 267
  • 405