0

Can someone be so kind and explain why do I get a squiggly error in Xcode when I try to use a constant property inside a closure?

I need to use a constant property in multiple UITextFields so I set PLACE_HOLDER to be a that constant but I get the following squiggly error when I try to use it inside a closure.

Value of type '(UserInputViewController) -> () -> UserInputViewController' has no member 'PLACE_HOLDER'

class UserInputViewController: UIViewController{
  // constant   
  let PLACE_HOLDER = "Some Text"

  // computed property for textField
  let textFieldOne: UITextField = {

    let textField1 = UITextField()
    textField1.placeholder = PLACE_HOLDER // error here
    // some other styles

    return textField1
  }()

  override func viewDidLoad(){}
}

Any idea why?

Sh_Khan
  • 93,445
  • 7
  • 57
  • 76
fs_tigre
  • 10,075
  • 12
  • 64
  • 127

1 Answers1

0

If you are about to access any property of your ViewController inside a closure before ViewController's initialisation, then you need to declare that variable as lazy:

lazy var textFieldOne: UITextField = { 
    let textField1 = UITextField()
    textField1.placeholder = self.PLACE_HOLDER  
    return textField1
}()
Lew Winczynski
  • 1,080
  • 1
  • 9
  • 19
Sh_Khan
  • 93,445
  • 7
  • 57
  • 76
  • @ Sh_Khan - Everything seem to be working after changing `let textFieldOne:UITextField = {}` to `lazy var textFieldOne:UITextField = {}` II don't quite understand `lazy variables` yet, is there something I should be aware in the meantime? Thanks – fs_tigre Dec 26 '19 at 21:30
  • 1
    https://theswiftdev.com/2018/12/17/lazy-initialization-in-swift/ and http://www.apeth.com/swiftBook/ch03.html#_lazy_initialization – Sh_Khan Dec 26 '19 at 21:33
  • 2
    In your original definition of textField1 you are referencing PLACE_HOLDER, which WILL BECOME a property once init() has been executed ( You can't access properties before init has completed). Without lazy you are referencing the property before it exists. `lazy` allows you to delay creating the property until you use it. – Mozahler Dec 26 '19 at 21:36