如何迅速理解设置为private的全局变量? [英] How is a global variable set to private understood in swift?

查看:241
本文介绍了如何迅速理解设置为private的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在完成一本书中的核心数据练习,它首先创建了一个单例的帮助程序类。我知道可以在课程范围之外创建全局变量,并且可以在整个项目中访问全局变量,但令我感到困惑的是,这本书中的示例创建了一个全局变量并将其设置为私有。我假设通过将变量设置为private,只有特定的类可以访问它。此私有全局变量是在helper类之外创建的,因此我认为该变量可被项目中的所有类访问,因此,不需要private关键字。任何人都可以通过确认我的假设是对的还是对的来帮助我。

I'm working through a Core Data exercise from a book and it starts out creating a helper class which is a singleton. I understand that global variables can be created outside of a class's scope and accessible throughout the project however where I'm confused is than an example from the book creates a global variable and sets it to private. I assumed that by setting a variable to private, it is only accessible to that specific class. This private global variable is created outside of the helper class so I assume its accessible by all classes in the project therefore the private keyword isn't necessary. Can anyone help by confirming if my assumptions are correct or incorrect as I'd really like to understand.

这是本书示例中的代码:

Here is the code from the book's example:

import Foundation

import CoreData


//this is a global variable accessible from any module or class
private let _sharedCDHelper = CDHelper()

class CDHelper: NSObject {

    // MARK: - SHARED INSTANCE
    class var shared: CDHelper {
        return _sharedCDHelper
    }
}


推荐答案

Swift中的私有全局变量是只能从声明该文件的文件中访问的全局变量。

A private global variable in Swift is a global that is only accessible from the file in which it is declared.

就在Swift中创建单例而言,使用的方法并没有遵循当前的最佳实践(也许有些过时了?)。

The book you are using isn't following current best-practice as far as creating singletons in Swift (perhaps it is a little out-dated?).

私有全局变量。您可以说:

There is no need for the private global variable. You can just say:

class CDHelper: NSObject {
// MARK: - SHARED INSTANCE
    static let shared = CDHelper()
}

这篇关于如何迅速理解设置为private的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆