Swift中的全局常量文件

Swift中的全局常量文件,第1张

Swift中的全局常量文件 结构作为名称空间

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        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5476670.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存