Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't reference self from within a lazy property in swift

I recently stumbled onto something weird in my code, I have programming in the same project for a few days but all of a sudden I tried to create a lazy property with this code:

import UIKit

class CategoryViewController: UICollectionViewController {

  lazy var searchController: UISearchController = {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(self.collectionView.frame), height: 44)
    return searchController
    }()
}

Now every time I try to reference self from with in the lazy block it produces this:

self.(<#NSObject#>)

and can't access none of the other properties.

If i try to hard-code them it produces:

UICollectionView? does not have a member named 'frame'

And the code above displays:

Extra argument 'width' in call

I already tried to rewrite the code and eliminating the derived data, build again but the error keeps persisting. Any ideas as to why it could happen?

Thanks in advance

Update autocomplete box:

enter image description here

like image 960
Jake Ortiz Avatar asked Nov 09 '22 21:11

Jake Ortiz


1 Answers

UICollectionView? does not have a member named 'frame'

See the question mark? That means this is an Optional. You cannot send any messages to an Optional until you unwrap it. So unwrap it: self.collectionView!.frame

EDIT The reason this worked before, and then your code broke, is that the Swift API changed. Apple does this a lot, so you have to "roll with the punches". You need to be ready for your code to break every time you upgrade Xcode. They have changed their minds three times about whether a UICollectionViewController's collectionView should be an Optional or not. And I am not at all convinced that their answer is correct even now.

Further edit Showing that autocompletion works:

enter image description here

like image 83
matt Avatar answered Nov 14 '22 21:11

matt