如何创建全局变量? [英] How to create a global variable?

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

问题描述

我有一个需要在我的 ViewController 之间共享的全局变量.

I have a global variable that needs to be shared among my ViewControllers.

在 Objective-C 中,我可以定义一个静态变量,但是我找不到在 Swift 中定义全局变量的方法.

In Objective-C, I can define a static variable, but I can't find a way to define a global variable in Swift.

你知道一种方法吗?

推荐答案

来自官方 Swift 编程 指南:

From the official Swift programming guide:

全局变量是在任何外部定义的变量函数、方法、闭包或类型上下文.全局常量和变量总是被延迟计算.

Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.

您可以在任何文件中定义它,并且可以在当前模块的任何地方访问它.因此,您可以在任何范围之外的文件中的某处定义它.不需要static,所有全局变量都是惰性计算的.

You can define it in any file and can access it in current module anywhere. So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily.

 var yourVariable = "someString"

您可以从当前模块的任何位置访问它.

You can access this from anywhere in the current module.

但是您应该避免这种情况,因为全局变量对应用程序状态不利,并且主要是错误的原因.

However you should avoid this as Global variables are not good for application state and mainly reason of bugs.

如本答案所示,在Swift 你可以将它们封装在 struct 中并且可以在任何地方访问.您也可以在 Swift 中定义静态变量或常量.封装在struct

As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere. You can define static variables or constant in Swift also. Encapsulate in struct

struct MyVariables {
    static var yourVariable = "someString"
}

你可以在任何类或任何地方使用这个变量

You can use this variable in any class or anywhere

let string = MyVariables.yourVariable
println("Global variable:(string)")

//Changing value of it
MyVariables.yourVariable = "anotherString"

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

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