I am using lazy var in my project at login time. When user first time successfully login that time lazy var userLoginInfo fetch data from the database first time and it displays correct data. When I perform login operation again that time it shows first time initialized login data. So How to reinitialize lazy var second time?
lazy var userLoginInfo:LoginInfo = {
return self.fetchLogin()
}()
The pair of braces at the end of the closure indicates that the closure is called once when the property is accessed the first time.
But it doesn't mean that you can't assign a new value to the property.
For example this is valid code
lazy var userLoginInfo : LoginInfo = {
return self.fetchLogin()
}()
func resetLoginInfo()
{
userLoginInfo = fetchLogin()
}
This might be useful if the variable is going to be changed rarely. If not a computed property as described in Josh's answer is the better choice.
I think its better to just use a read only computed property here instead of lazy so that every time you ask for the user it returns the current value in the database.
var userLoginInfo:LoginInfo {
return self.fetchLogin()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With