如何創建全局變量?

[英]How to create a global variable?


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

我有一個全局變量,需要在我的ViewControllers之間共享。

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

在Objective-C中,我可以定義一個靜態變量,但是我找不到一種方法來定義Swift中的全局變量。

Do you know of a way to do it?

你知道怎么做嗎?

2 个解决方案

#1


149  

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

如swift中的答案所示,您可以將它們封裝在struct中,並可以訪問任何地方。您也可以在swift中定義靜態變量或常量。的封裝結構

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"

#2


13  

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

在任何方法或閉包之外定義的全局變量可以使用private關鍵字來限制范圍。

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/10/04/e71cd47f575bc494c692a324017100fd.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com