小编典典

Swift 中的全局常量文件

all

在我的 Objective-C 项目中,我经常使用全局常量文件来存储通知名称和NSUserDefaults. 它看起来像这样:

@interface GlobalConstants : NSObject

extern NSString *someNotification;

@end

@implementation GlobalConstants

NSString *someNotification = @"aaaaNotification";

@end

我如何在 Swift 中做同样的事情?


阅读 112

收藏
2022-03-29

共1个答案

小编典典

结构体作为命名空间

IMO 处理此类常量的最佳方法是创建一个 Struct。

struct Constants {
    static let someNotification = "TEST"
}

然后,例如,在您的代码中这样调用它:

print(Constants.someNotification)

嵌套

如果您想要一个更好的组织,我建议您使用分段子结构

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

现实世界的例子

这只是一个技术解决方案,我的代码中的实际实现看起来更像:

struct GraphicColors {

    static let grayDark = UIColor(0.2)
    static let grayUltraDark = UIColor(0.1)

    static let brown  = UIColor(rgb: 126, 99, 89)
    // etc.
}

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
        }
    }
}
2022-03-29