Xcode: Swift—如何根据执行环境声明具有不同值的变量/常量?

时间:2023-01-22 12:58:57

I am trying to figure out how to handle variables/constants for different environments, e.g. development(or debug) and release. For instance when executing a unit test the url for a web service should point to the localhost, but in the final product it should point to the public api host.

我正在研究如何处理不同环境的变量/常量,例如开发(或调试)和发布。例如,在执行单元测试时,web服务的url应该指向本地主机,但是在最终的产品中,它应该指向公共api主机。

I have read something about setting the Swift Compiler - Custom Flags Debug settings to -DDEBUG and then in the code declare the variable like so:

我读过一些关于设置Swift编译器的内容——自定义标记调试设置为- ddebug,然后在代码中像这样声明变量:

#if DEBUG
  let url = "http://localhost"
#else
  let url = "https://api.example.com"
#endif

But that didn't work. When running a unit test the url is never set to http://localhost. Did I miss something here?

但这并不工作。运行单元测试时,url永远不会被设置为http://localhostor。我错过什么了吗?

1 个解决方案

#1


2  

Edit project scheme...

编辑项目计划…

Xcode: Swift—如何根据执行环境声明具有不同值的变量/常量?

Define your environment variable: Xcode: Swift—如何根据执行环境声明具有不同值的变量/常量?

定义你的环境变量:

And finally check if was defined for the schema that you are dealing with:

最后检查是否为你正在处理的模式定义了:

var baseURL:String{
    get{
        if let _ = ProcessInfo().environment["LOCAL_MOCK_SERVER"]{
            return "http:/localhost:3000"
        } else{
            return "https://api.fixer.io"
        }

    }
}

#1


2  

Edit project scheme...

编辑项目计划…

Xcode: Swift—如何根据执行环境声明具有不同值的变量/常量?

Define your environment variable: Xcode: Swift—如何根据执行环境声明具有不同值的变量/常量?

定义你的环境变量:

And finally check if was defined for the schema that you are dealing with:

最后检查是否为你正在处理的模式定义了:

var baseURL:String{
    get{
        if let _ = ProcessInfo().environment["LOCAL_MOCK_SERVER"]{
            return "http:/localhost:3000"
        } else{
            return "https://api.fixer.io"
        }

    }
}