在我的Objective-C项目中,我经常使用一个全局常量文件来存储像通知名称和NSUserDefaults键这样的东西。它看起来是这样的:
@interface GlobalConstants : NSObject
extern NSString *someNotification;
@end
@implementation GlobalConstants
NSString *someNotification = @"aaaaNotification";
@end
我如何在Swift中做完全相同的事情?
考虑枚举。这些可以在逻辑上分解为单独的用例。
enum UserDefaultsKeys: String {
case SomeNotification = "aaaaNotification"
case DeviceToken = "deviceToken"
}
enum PhotoMetaKeys: String {
case Orientation = "orientation_hv"
case Size = "size"
case DateTaken = "date_taken"
}
一个独特的好处发生在你有一个互斥选项的情况下,比如:
for (key, value) in photoConfigurationFile {
guard let key = PhotoMetaKeys(rawvalue: key) else {
continue // invalid key, ignore it
}
switch (key) {
case.Orientation: {
photo.orientation = value
}
case.Size: {
photo.size = value
}
}
}
在本例中,您将收到一个编译错误,因为您没有处理PhotoMetaKeys.DateTaken的情况。
颜色
extension UIColor {
static var greenLaPalma: UIColor {
return UIColor(red:0.28, green:0.56, blue:0.22, alpha:1.00)
}
}
字体
enum CustomFontType: String {
case avenirNextRegular = "AvenirNext-Regular",
avenirDemiBold = "AvenirNext-DemiBold"
}
extension UIFont {
static func getFont(with type: CustomFontType, size: CGFloat) -> UIFont {
let font = UIFont(name: type.rawValue, size: size)!
return font
}
}
对于其他-一切都与接受的答案相同。