In my work, I came across the fact that I often need to store some properties as long as the application is running and so that I can access them from different files and classes.
Here's one example. I authorize a user in Google Drive and I need to save this user to a variable in order to refer to him in another class. I declare global constant over the class, but I'm not sure if this is a good practice. If I declare this variable inside a class and access it through an instance of the class, my application does not work.
public var googleUser: GIDGoogleUser?
class MyViewController: UIViewController {
...
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!) {
googleUser = user //Here I save user to googleUser property
}
...
}
class GoogleDriveService {
...
private lazy var driveService: GTLRDriveService = {
let service = GTLRDriveService()
if let user = googleUser { //Here I use googleUser property
service.authorizer = user.authentication.fetcherAuthorizer()
}
service.shouldFetchNextPages = true
service.isRetryEnabled = true
return service
}()
//Then I use the driveService property in some methods like fetchFileList, download and other, which I call from different View Controllers referring to an instance of the GoogleDriveService class
...
}