Why can the keyword “weak” only be applied to class and class-bound protocol types

后端 未结 11 1306
清酒与你
清酒与你 2020-12-13 03:14

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

11条回答
  •  执念已碎
    2020-12-13 03:58

    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
       }()
    }
    

提交回复
热议问题