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

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

问题描述



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



你知道一种方法吗?

解决方案

从swift编程指南


全局变量是在任何
函数,方法,闭包或类型上下文。全局常量和
变量总是延迟计算


您可以在任何文件中定义它,并且可以在当前 module 任何地方。
所以你可以在任何范围之外的文件中的某个地方定义它。没有必要使用 static ,并且所有全局变量都会被延迟计算。

  var yourVariable =someString

,您可以从当前模块的任何地方访问。



然而,您应该避免这种情况,因为全局变量对于应用程序状态并不好,并且主要是bug的原因。



回答
在swift中你可以封装它们在 struct 中,并且可以在任何地方访问。
您也可以在swift中定义静态变量或常量。封装在 struct



  struct MyVariables {
static var yourVariable =someString
}

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

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

//改变它的值
MyVariables.yourVariable =anotherString


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

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

Do you know of a way to do it?

解决方案

From 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

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"

and you can access from anywhere in current module.

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

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天全站免登陆