在Swift中声明全局variables
我想创build一个可以在整个应用程序(AppDelegate,ViewController类,TableViewController类等)访问的自定义对象的全局数组。 我研究了一种方法来做到这一点,但还没有find答案。 我曾尝试使数组为公共范围,但我得到一个编译器警告说, Declaring public variable from internal class
,当我尝试访问它在不同的文件中,我得到一个错误,说Use of unresolved identifier 'arrayObjectives'
我将如何去使全局访问应用程序中的所有文件的数组,我将在哪里实例化该数组?
从Swift编程语言 –
全局variables是在任何函数,方法,闭包或types上下文之外定义的variables
所以你可以直接在import
语句之后的任何文件的顶部声明你的variables。
不过,我build议你认真重新考虑。 一般来说全局variables不是一个好主意。 您最好使用单例属性或使用dependency injection。
你的第二个问题“我将在哪里实例化数组? 是全局变差的原因之一 – 它们的生命周期在其他对象方面没有很好的定义。 首次使用时初始化的单例消除了这个问题。
你可以像这样设置全局数组:
import UIKit var abc : String = String()
你可以在任何其他文件中访问它:
abc = "ABC"
尝试使用下面的方法创build一个新的Swift文件:
struct Constants { static let appName: String = "My App" struct Colors { static let colorTextStandard = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.3) //#000000 } struct Data { static var myStrings = [String]() // Yea, this is not a constant, but that's alright... } }
然后,您可以使用以下参考这些全局常量(或者可以使它们variables):
Constants.appName
要么
Constants.Colors.colorTextStandard
要么
Constants.Data.myStrings = [stringOne, stringTwo]
我就是这么做的
class MessageViewCell { struct MessageViewCellHeightCache { static var cache: [String:CGFloat] = Dictionary<String, CGFloat>() } }
我访问它如下:
MessageViewCell.MessageViewCellHeightCache.cache["first"] = 12.0