Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reinitialize lazy var in swift?

Tags:

ios

swift

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()
    }()
like image 868
Pranit Avatar asked Jan 29 '23 03:01

Pranit


2 Answers

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.

like image 161
vadian Avatar answered Jan 31 '23 23:01

vadian


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()
}
like image 23
Josh Homann Avatar answered Jan 31 '23 22:01

Josh Homann