栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Swift中的全局常量文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484531.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号