I'm trying to achieve a seemingly easy thing: initialize constant variable using another one from the same class which is inheriting from UIViewController. I had 2 ideas that worked, but have their problems and don't seem to be the best solution.
Idea 1 - problem: isn't constant
class MyViewController: UIViewController {
let db = Firestore.firestore()
let uid: String = UserDefaults.standard.string(forKey: "uid")!
lazy var userDocRef = db.collection("users").document(uid)
}
Idea 2 - problem: isn't constant and is optional
class MyViewController: UIViewController {
let db = Firestore.firestore()
let uid: String = UserDefaults.standard.string(forKey: "uid")!
var userDocRef: DocumentReference?
override func viewDidLoad() {
super.viewDidLoad()
userDocRef = db.collection("users").document(uid)
}
}
I think it should be possible to achieve that by overriding init()
. I've tried couple of implementations I found Googling, but everyone I've tried gave me some kind of error. Few examples:
convenience init() {
self.init(nibName:nil, bundle:nil) // error: Argument passed to call that takes no arguments
userDocRef = db.collection(K.Firestore.usersCollection).document(uid)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)! // Property 'self.userDocRef' not initialized at super.init call
}
init() {
super.init(nibName: nil, bundle: nil) // Property 'self.userDocRef' not initialized at super.init call
userDocRef = db.collection(K.Firestore.usersCollection).document(uid)
}
I'm guessing I'm either missing something or those are outdated? I'm surprised such a simple task as overriding initializer is such a bother. What is the proper way to do it?