全局常量文件在Swift中 [英] Global constants file in Swift
本文介绍了全局常量文件在Swift中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Objective-C项目中,我经常使用全局常量文件来存储诸如 NSUserDefaults
的通知名称和密钥之类的内容。它看起来像这样:
In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults
. It looks something like this:
@interface GlobalConstants : NSObject
extern NSString *someNotification;
@end
@implementation GlobalConstants
NSString *someNotification = @"aaaaNotification";
@end
如何在Swift中做同样的事情?
How do I do exactly the same thing in Swift?
推荐答案
IMO处理这类常量的最佳方法是创建一个Struct。
IMO the best way to deal with that type of constants is to create a Struct.
struct Constants {
static let someNotification = "TEST"
}
然后,例如,在您的代码中将其称为:
Then, for example, call it like this in your code:
print(Constants.someNotification)
编辑:如果你想要一个更好的组织我建议你使用segmented子结构
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()
}
}
然后你就可以了我们例如, K.Path.Tmp
Then you can just use for instance K.Path.Tmp
这篇关于全局常量文件在Swift中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文