使用全局变量和常量是好的做法吗? (Swift 5)

Is it good practice to use global variables and constants? (Swift 5)

在我的工作中,我发现只要应用程序是 运行,我经常需要存储一些属性,以便我可以从不同的文件和 classes 访问它们.

这是一个例子。我在 Google Drive 中授权了一个用户,我需要将该用户保存到一个变量中以便在另一个 class 中引用他。我在 class 上声明了全局常量,但我不确定这是否是一个好的做法。如果我在 class 中声明此变量并通过 class 的实例访问它,我的应用程序将无法运行。

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
    ...
}

您可以使用结构的静态变量来更优雅地执行此操作:

struct Repository {
    static var googleUser: String?
}

和 access/set googleUser 使用结构类型:

Repository.googleUser = user

或者更好,像这样使用单例 class:

class Repository {
    static let shared = Repository()
    var googleUser: String?
}

那你就可以直接用了:

Repository.shared.googleUser = user

或者将单例实例注入 class 想要使用的 googleUser.