ios Swift 中的全局常量文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26252233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:04:18  来源:igfitidea点击:

Global constants file in Swift

iosobjective-cswift

提问by user1028028

In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults. It looks something like this:

在我的 Objective-C 项目中,我经常使用全局常量文件来存储诸如通知名称和NSUserDefaults. 它看起来像这样:

@interface GlobalConstants : NSObject

extern NSString *someNotification;

@end

@implementation GlobalConstants

NSString *someNotification = @"aaaaNotification";

@end

How do I do exactly the same thing in Swift?

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

回答by Francescu

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

回答by Anish Parajuli ?

I am abit late to the party.

我参加聚会有点晚了。

No matter here's how i manage the constants file so that it makes more sense to developers while writing code in swift.

无论我在这里如何管理常量文件,以便在快速编写代码时对开发人员更有意义。

FOR URL:

网址:

//URLConstants.swift

  struct APPURL {

    private struct Domains {
        static let Dev = "http://test-dev.cloudapp.net"
        static let UAT = "http://test-UAT.com"
        static let Local = "192.145.1.1"
        static let QA = "testAddress.qa.com"
    }

    private  struct Routes {
        static let Api = "/api/mobile"
    }

    private  static let Domain = Domains.Dev
    private  static let Route = Routes.Api
    private  static let BaseURL = Domain + Route

    static var FacebookLogin: String {
        return BaseURL  + "/auth/facebook"
    }
}

For CUSTOMFONTS:

对于自定义字体:

//FontsConstants.swift
struct FontNames {

    static let LatoName = "Lato"
    struct Lato {
        static let LatoBold = "Lato-Bold"
        static let LatoMedium = "Lato-Medium"
        static let LatoRegular = "Lato-Regular"
        static let LatoExtraBold = "Lato-ExtraBold"
    }
}

FOR ALL THE KEYS USED IN APP

对于应用程序中使用的所有键

//KeyConstants.swift
    struct Key {

        static let DeviceType = "iOS"
        struct Beacon{
            static let ONEXUUID = "xxxx-xxxx-xxxx-xxxx"
        }

        struct UserDefaults {
            static let k_App_Running_FirstTime = "userRunningAppFirstTime"
        }

        struct Headers {
            static let Authorization = "Authorization"
            static let ContentType = "Content-Type"
        }
        struct Google{
            static let placesKey = "some key here"//for photos
            static let serverKey = "some key here"
        }

        struct ErrorMessage{
            static let listNotFound = "ERROR_LIST_NOT_FOUND"
            static let validationError = "ERROR_VALIDATION"
        }
    }

FOR COLOR CONSTANTS:

对于颜色常数:

//ColorConstants.swift
struct AppColor {

    private struct Alphas {
        static let Opaque = CGFloat(1)
        static let SemiOpaque = CGFloat(0.8)
        static let SemiTransparent = CGFloat(0.5)
        static let Transparent = CGFloat(0.3)
    }

    static let appPrimaryColor =  UIColor.white.withAlphaComponent(Alphas.SemiOpaque)
    static let appSecondaryColor =  UIColor.blue.withAlphaComponent(Alphas.Opaque)

    struct TextColors {
        static let Error = AppColor.appSecondaryColor
        static let Success = UIColor(red: 0.1303, green: 0.9915, blue: 0.0233, alpha: Alphas.Opaque) 
    }

    struct TabBarColors{
        static let Selected = UIColor.white
        static let NotSelected = UIColor.black
    }

    struct OverlayColor {
        static let SemiTransparentBlack = UIColor.black.withAlphaComponent(Alphas.Transparent)
        static let SemiOpaque = UIColor.black.withAlphaComponent(Alphas.SemiOpaque)
        static let demoOverlay = UIColor.black.withAlphaComponent(0.6)
    }
}

You can wrap these all files in a common group named Constantsin your Xcode Project.

您可以将这些所有文件包装在 Xcode 项目中名为Constants的公共组中。

And for more watch this video

欲了解更多,请观看此视频

回答by Antonio

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 中的全局变量不是变量

回答by Kirit Vaghela

Constant.swift

常量.swift

import Foundation

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

ViewController.swift

视图控制器.swift

var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)

回答by William Entriken

Consider enumerations. These can be logically broken up for separate use cases.

考虑枚举。这些可以在逻辑上分解为单独的用例。

enum UserDefaultsKeys: String {
    case SomeNotification = "aaaaNotification"
    case DeviceToken = "deviceToken"
}

enum PhotoMetaKeys: String {
    case Orientation = "orientation_hv"
    case Size = "size"
    case DateTaken = "date_taken"
}

One unique benefit happens when you have a situation of mutually exclusive options, such as:

当您遇到互斥选项的情况时,会产生一个独特的好处,例如:

for (key, value) in photoConfigurationFile {
    guard let key = PhotoMetaKeys(rawvalue: key) else {
        continue // invalid key, ignore it
    }
    switch (key) {
    case.Orientation: {
        photo.orientation = value
    }
    case.Size: {
        photo.size = value
    }
    }
}

In this example, you will receive a compile error because you have not handled the case of PhotoMetaKeys.DateTaken.

在这个例子中,你会收到一个编译错误,因为你没有处理PhotoMetaKeys.DateTaken.

回答by ChikabuZ

Or just in GlobalConstants.swift:

或者只是在 GlobalConstants.swift 中:

import Foundation

let someNotification = "aaaaNotification"

回答by Jacob R

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 e.g. write:

任何时候您想使用此类中的某些内容时,您都可以这样写:

TestClass.sharedInstance.number = 1

If you now write println(TestClass.sharedInstance.number)from anywhere in your project you will print 1to the log. This works for all kinds of Objects.

如果您现在println(TestClass.sharedInstance.number)从项目中的任何位置写入,您将打印1到日志。这适用于所有类型的对象。

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

回答by Vinay Krishna Gupta

What I did in my Swift project
1: Create new Swift File
2: Create a struct and static constant in it.
3: For Using just use YourStructName.baseURL

我在我的 Swift 项目中做了什么
1:创建新的 Swift 文件
2:在其中创建一个结构体和静态常量。
3:使用只使用 YourStructName.baseURL

Note: After Creating initialisation takes little time so it will show in other viewcontrollers after 2-5 seconds.

注意:在创建初始化后花费的时间很少,因此它会在 2-5 秒后显示在其他视图控制器中。

import Foundation

    struct YourStructName {
    static let MerchantID = "XXX"
    static let MerchantUsername = "XXXXX"
    static let ImageBaseURL = "XXXXXXX"
    static let baseURL = "XXXXXXX"
    }

回答by B. Shoe

For notifications you can use extension, something like this:

对于通知,您可以使用扩展程序,如下所示:

extension Notification.Name {
    static let testNotification = "kTestNotification"
}

And use it like NotificationCenter.default.post(name: .testNotification, object: nil)

并使用它 NotificationCenter.default.post(name: .testNotification, object: nil)

回答by Ale Mohamad

To have global constants in my apps, this is what I do in a separate Swiftfile:

要在我的应用程序中使用全局常量,这就是我在单独的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"
    }
}

It's easy to use, and to call everywhere like this:

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

print(Config.Notifications.awareUser)