Sanket Sanket -4 years ago 114
iOS Question

How to access computed variable inside computed initializer in swift 3?

In my swift 3 program shown below, I want to access computed variable 'darkColor' inside computed initializer. But swift 3 compiler giving me an error: instance member 'darkColor' cannot be used on type 'LoginViewController'

import UIKit

class LoginViewController: BaseViewController, UITextFieldDelegate {

// FIXME: - computed variables
private var darkColor: UIColor {
return UIColor(hex: 0x0083C5, alpha: 1)
}

// FIXME: - create views / computed initializers
lazy var textEmail: UITextField = {
let textField = UITextField()
textField.placeholder = "Email"
textField.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
textField.textColor = darkColor // here I'm getting error that "instance member 'darkColor' cannot be used on type 'LoginViewController'"
textField.keyboardType = .emailAddress
textField.autocorrectionType = .no
textField.translatesAutoresizingMaskIntoConstraints = false
textField.delegate = self
return textField
}()

let emailUnderline: UIView = {
let view = UIView()
view.backgroundColor = darkColor // here I'm getting error that "instance member 'darkColor' cannot be used on type 'LoginViewController'"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()

// FIXME: - life cycle
override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.white
}
}

Answer Source

There are few possible way to use it during computed variable init

  1. Use self.darkColor for lazy variable since it will only get created when access (cant access self during initialize of the class)
  2. Change to class variable, but this will affect all of the instances of LoginViewController
  3. Move the let darkColor {...} outside the class scope will make it become global constant
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download