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

@interface GlobalConstants : NSObject

extern NSString *someNotification;

@end

@implementation GlobalConstants

NSString *someNotification = @"aaaaNotification";

@end

我如何在Swift中做完全相同的事情?


当前回答

正如其他人所提到的,在类之外声明的任何东西都是全局的。

你也可以创建单例对象:

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

当你想要使用这个类中的一些东西时,你可以这样写:

TestClass.sharedInstance.number = 1

如果您现在从项目的任何地方写入println(TestClass.sharedInstance.number),您将向日志中输出1。这适用于所有类型的对象。

tl;dr:任何时候你想让一个类中的所有东西都是全局的,在类中添加静态let sharedInstance = YourClassName(),并用前缀YourClassName.sharedInstance来处理类的所有值

其他回答

向苹果学习是最好的方法。

例如,苹果的键盘通知:

extension UIResponder {

    public class let keyboardWillShowNotification: NSNotification.Name

    public class let keyboardDidShowNotification: NSNotification.Name

    public class let keyboardWillHideNotification: NSNotification.Name

    public class let keyboardDidHideNotification: NSNotification.Name

}

现在我向苹果学习:

extension User {
    /// user did login notification
    static let userDidLogInNotification = Notification.Name(rawValue: "User.userDidLogInNotification")
}

更重要的是,NSAttributedString.Key.foregroundColor:

extension NSAttributedString {

    public struct Key : Hashable, Equatable, RawRepresentable {

        public init(_ rawValue: String)

        public init(rawValue: String)
    }
}

extension NSAttributedString.Key {

    /************************ Attributes ************************/

    @available(iOS 6.0, *)
    public static let foregroundColor: NSAttributedString.Key // UIColor, default blackColor

}

现在我向苹果学习:

extension UIFont {

    struct Name {

    }

}

extension UIFont.Name {

    static let SFProText_Heavy = "SFProText-Heavy"
    static let SFProText_LightItalic = "SFProText-LightItalic"
    static let SFProText_HeavyItalic = "SFProText-HeavyItalic"

}

用法:

let font = UIFont.init(name: UIFont.Name.SFProText_Heavy, size: 20)

向苹果学习是每个人都可以做的事情,可以很容易地提高你的代码质量。

或者只在GlobalConstants.swift中:

import Foundation

let someNotification = "aaaaNotification"

为了在我的应用程序中有全局常量,这是我在一个单独的Swift文件中所做的:

import Foundation

struct Config {
    static let baseURL = "https://api.com"

    static APIKeys {
        static let token = "token"
        static let user = "user"
    }

    struct Notifications {
        static let awareUser = "aware_user"
    }
}

它很容易使用,并且可以像这样调用任何地方:

print(Config.Notifications.awareUser)

Swift 4版本

如果您想为NotificationCenter创建一个名称:

extension Notification.Name {
    static let updateDataList1 = Notification.Name("updateDataList1")
}

订阅通知:

NotificationCenter.default.addObserver(self, selector: #selector(youFunction), name: .updateDataList1, object: nil)

发送通知:

NotificationCenter.default.post(name: .updateDataList1, object: nil)

如果你只是想要一个有变量的类:

class Keys {
    static let key1 = "YOU_KEY"
    static let key2 = "YOU_KEY"
}

Or:

struct Keys {
    static let key1 = "YOU_KEY"
    static let key2 = "YOU_KEY"
}

结构作为命名空间

在我看来,处理这类常量的最好方法是创建一个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.
}

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