richy richy - 6 months ago 17
Swift Question

Accessing inherited objects in lazy initializing swift

Just wondering why I can't access the inherited object collectionView when lazy initializing:

class FunCollectionLayout : UICollectionViewFlowLayout {
var middleSection:Int = {
let sectionCount = self.collectionView!.numberOfSections()
return sectionCount/2
}()

func testFunc() {
print((self.collectionView?.numberOfSections())! / 2)
}
}


The error is:

Value of type 'NSObject -> () -> FunCollectionLayout' has no member 'collectionView'

Answer

You are simply missing the lazy declaration attribute.

  lazy var middleSection:Int = {
    let sectionCount = self.collectionView!.numberOfSections()
    return sectionCount/2
  }()

But you are missing the point by not making this a computed property.

  var middleSection: Int {
    let sectionCount = self.collectionView!.numberOfSections()
    return sectionCount / 2
  }

Keep it dynamic, keep it in sync with the collectionView, make it a computed property.

Comments