本文介绍了在Swift中声明全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以在整个应用程序中访问的全局自定义对象数组(AppDelegate,ViewController类,TableViewController类等)。我已经研究过一种方法,但还没有找到答案。我已经尝试过为数组提供一个公共范围,但我得到一个编译器警告,说明从内部类声明公共变量,当我尝试在另一个文件中访问它时,我收到一条错误,上面写着使用未解析的标识符'arrayObjectives'

I want to make a global array of custom objects that can be accessed throughout the app (AppDelegate, ViewController classes, TableViewController classes, etc). I have researched for a way to do it, but have not found an answer. I have tried making giving the array a public scope, but I get a complier warning which says Declaring public variable from internal class and when I try to access it in a different file, I get an error that says Use of unresolved identifier 'arrayObjectives'

我如何全局制作该数组可以访问应用程序中的所有文件以及在哪里实例化该数组?

How would I go about making that array globally accessible to all files in the application and where would I instantiate that array?

推荐答案

来自 -

全局变量是在任何
函数,方法,闭包或类型上下文之外定义的变量

因此,您可以在 import 语句之后直接在任何文件的顶部声明您的变量。

So you can simply declare your variable at the top of any file straight after the import statements.

但是,我建议你认真重新考虑。通常全局变量不是一个好主意。您最好使用单例属性或使用依赖注入。

However, I would suggest you seriously reconsider. Generally globals aren't a good idea. You are better off with properties on a singleton or using dependency injection.

你的第二个问题我将在哪里实例化数组?全局变量是坏的原因之一 - 它们的生命周期没有根据你的其他对象定义。在首次使用时初始化的单例消除了此问题。

Your second question "where would I instantiate the array?" is part of the reason why globals are bad - their lifecycle isn't well defined in terms of your other objects. A singleton that is initialised on first use eliminates this issue.

这篇关于在Swift中声明全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:34
查看更多