Swiftのグローバル定数ファイル 質問する

Swiftのグローバル定数ファイル 質問する

私の Objective-C プロジェクトでは、通知名やキーなどを保存するためにグローバル定数ファイルをよく使用しますNSUserDefaults。次のような形式になります。

@interface GlobalConstants : NSObject

extern NSString *someNotification;

@end

@implementation GlobalConstants

NSString *someNotification = @"aaaaNotification";

@end

Swift でまったく同じことを行うにはどうすればよいでしょうか?

ベストアンサー1

名前空間としての構造体

私の考えでは、このタイプの定数を処理する最善の方法は、構造体を作成することです。

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

おすすめ記事