Self is not accessible in Closure

Hi guys,

I have a question, I tried to declare a view in controller

Let view = {
let cv = UICollectionView()
cv.delegate = self
}()

what I found was that self is not accessible in the clousure, then I changed it to

Lazy var view = {
let cv = UICollectionView()
cv.delegate = self
}()

Works smoothly. Can anyone explain this a bit why this happens?

@jiang Thanks very much for your question!

lazy defers the initialization of the variable, and guarantees that it will only be used when self is instantiated.

All properties in Swift must be initialized before self is initialized. The first snippet is a property and you’re trying to reference self before it’s initialized.

I hope this helps!

All the best!

2 Likes

Thanks for your explaination

@jiang No problem! I’m happy to have helped!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.