When I\'m declaring variables as weak
in Swift, I sometimes get the error message from Xcode:
\'weak\' may only be applied to class and
I find out in one case where you even have class type but still you get this error message.
For example,
class MyVC: UIViewController {
var myText: UITextView = {
[weak self]
let text = UITextView()
// some codes using self
return text
}()
}
Here an UITextView
object is returned from an anonymous block as initialization of var myText
. I got the same type of error message. To resolve the issue, the var
has to be marked as lazy
:
class MyVC: UIViewController {
lasy var myText: UITextView = {
[weak self]
let text = UITextView()
// some codes using self
return text
}()
}