本文翻译自:Global constants file in Swift
In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults
. 在我的Objective-C项目中,我经常使用全局常量文件来存储诸如通知名称和NSUserDefaults
键之类的NSUserDefaults
。 It looks something like this: 看起来像这样:
@interface GlobalConstants : NSObject
extern NSString *someNotification;
@end
@implementation GlobalConstants
NSString *someNotification = @"aaaaNotification";
@end
How do I do exactly the same thing in Swift? 在Swift中,我该怎么做?
参考:https://stackoom.com/question/1m9P7/Swift中的全局常量文件
IMO the best way to deal with that type of constants is to create a Struct. IMO处理此类常量的最佳方法是创建Struct。
struct Constants {
static let someNotification = "TEST"
}
Then, for example, call it like this in your code: 然后,例如,在您的代码中这样调用它:
print(Constants.someNotification)
If you want a better organization I advise you to use segmented sub structs 如果您想要一个更好的组织,我建议您使用分段的子结构
struct K {
struct NotificationKey {
static let Welcome = "kWelcomeNotif"
}
struct Path {
static let Documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
static let Tmp = NSTemporaryDirectory()
}
}
Then you can just use for instance K.Path.Tmp
然后,您可以仅使用例如K.Path.Tmp
This is just a technical solution, the actual implementation in my code looks more like: 这只是一个技术解决方案,我的代码中的实际实现看起来更像:
struct GraphicColors {
static let grayDark = UIColor(0.2)
static let grayUltraDark = UIColor(0.1)
static let brown = UIColor(rgb: 126, 99, 89)
// etc.
}
and 和
enum Env: String {
case debug
case testFlight
case appStore
}
struct App {
struct Folders {
static let documents: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
static let temporary: NSString = NSTemporaryDirectory() as NSString
}
static let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
static let build: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
// This is private because the use of 'appConfiguration' is preferred.
private static let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
// This can be used to add debug statements.
static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
static var env: Env {
if isDebug {
return .debug
} else if isTestFlight {
return .testFlight
} else {
return .appStore
}
}
}
Or just in GlobalConstants.swift: 或仅在GlobalConstants.swift中:
import Foundation
let someNotification = "aaaaNotification"
Although I prefer @Francescu's way (using a struct with static properties), you can also define global constants and variables: 尽管我更喜欢@Francescu的方式(使用具有静态属性的结构),但是您也可以定义全局常量和变量:
let someNotification = "TEST"
Note however that differently from local variables/constants and class/struct properties, globals are implicitly lazy, which means they are initialized when they are accessed for the first time. 但是请注意,与局部变量/常量和类/结构属性不同,全局变量是隐式惰性的,这意味着它们在首次访问时会被初始化。
Suggested reading: Global and Local Variables , and also Global variables in Swift are not variables 建议阅读: 全局和局部变量 ,以及Swift中的全局变量都不是变量
Constant.swift 恒速
import Foundation
let kBaseURL = NSURL(string: "http://www.example.com/")
ViewController.swift ViewController.swift
var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)
Like others have mention anything declared outside a class is global. 就像其他人提到的那样,在类之外声明的任何内容都是全局的。
You can also create singletons: 您还可以创建单例:
class TestClass {
static let sharedInstance = TestClass()
// Anything else goes here
var number = 0
}
Any time you want to use something from this class you eg write: 每当您想使用此类中的内容时,都可以编写以下代码:
TestClass.sharedInstance.number = 1
If you now write println(TestClass.sharedInstance.number)
from anywhere in your project you will print 1
to the log. 如果现在从项目的任何位置写入println(TestClass.sharedInstance.number)
,则将1
打印到日志中。 This works for all kinds of Objects. 这适用于各种对象。
tl;dr: Any time you want to make everything in a class global, add static let sharedInstance = YourClassName()
to the class, and address all values of the class with the prefix YourClassName.sharedInstance
tl; dr:任何时候您都想使一个类中的所有内容变为全局,将static let sharedInstance = YourClassName()
到该类中,并使用前缀YourClassName.sharedInstance
寻址该类的所有值。