richy
richy

Reputation: 2815

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'

Upvotes: 0

Views: 194

Answers (1)

Price Ringo
Price Ringo

Reputation: 3440

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.

Upvotes: 1

Related Questions