Swift中的全局常量文件

本文翻译自:Global constants file in Swift

In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults . 在我的Objective-C项目中,我经常使用全局常量文件来存储诸如通知名称和NSUserDefaults键之类的NSUserDefaults It looks something like this: 看起来像这样:

@interface GlobalConstants : NSObject

extern NSString *someNotification;

@end

@implementation GlobalConstants

NSString *someNotification = @"aaaaNotification";

@end

How do I do exactly the same thing in Swift? 在Swift中,我该怎么做?


#1楼

参考:https://stackoom.com/question/1m9P7/Swift中的全局常量文件


#2楼

Structs as namespace 结构作为名称空间

IMO the best way to deal with that type of constants is to create a Struct. IMO处理此类常量的最佳方法是创建Struct。

struct Constants {
    static let someNotification = "TEST"
}

Then, for example, call it like this in your code: 然后,例如,在您的代码中这样调用它:

print(Constants.someNotification)

Nesting 套料

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

Then you can just use for instance K.Path.Tmp 然后,您可以仅使用例如K.Path.Tmp

Real world example 现实世界的例子

This is just a technical solution, the actual implementation in my code looks more like: 这只是一个技术解决方案,我的代码中的实际实现看起来更像:

struct GraphicColors {

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

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

and


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

#3楼

Or just in GlobalConstants.swift: 或仅在GlobalConstants.swift中:

import Foundation

let someNotification = "aaaaNotification"

#4楼

Although I prefer @Francescu's way (using a struct with static properties), you can also define global constants and variables: 尽管我更喜欢@Francescu的方式(使用具有静态属性的结构),但是您也可以定义全局常量和变量:

let someNotification = "TEST"

Note however that differently from local variables/constants and class/struct properties, globals are implicitly lazy, which means they are initialized when they are accessed for the first time. 但是请注意,与局部变量/常量和类/结构属性不同,全局变量是隐式惰性的,这意味着它们在首次访问时会被初始化。

Suggested reading: Global and Local Variables , and also Global variables in Swift are not variables 建议阅读: 全局和局部变量 ,以及Swift中的全局变量都不是变量


#5楼

Constant.swift 恒速

import Foundation

let kBaseURL = NSURL(string: "http://www.example.com/")

ViewController.swift ViewController.swift

var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)

#6楼

Like others have mention anything declared outside a class is global. 就像其他人提到的那样,在类之外声明的任何内容都是全局的。

You can also create singletons: 您还可以创建单例:

class TestClass {
    static let sharedInstance = TestClass()
    // Anything else goes here
    var number = 0
}

Any time you want to use something from this class you eg write: 每当您想使用此类中的内容时,都可以编写以下代码:

TestClass.sharedInstance.number = 1

If you now write println(TestClass.sharedInstance.number) from anywhere in your project you will print 1 to the log. 如果现在从项目的任何位置写入println(TestClass.sharedInstance.number) ,则将1打印到日志中。 This works for all kinds of Objects. 这适用于各种对象。

tl;dr: Any time you want to make everything in a class global, add static let sharedInstance = YourClassName() to the class, and address all values of the class with the prefix YourClassName.sharedInstance tl; dr:任何时候您都想使一个类中的所有内容变为全局,将static let sharedInstance = YourClassName()到该类中,并使用前缀YourClassName.sharedInstance寻址该类的所有值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值