Xcode: Swift - How do I declare a variable/constant with different values depending on the execution environment?

强颜欢笑 提交于 2019-12-23 15:12:55

问题


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.

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:

#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?


回答1:


Edit project scheme...

Define your environment variable:

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

    }
}


来源:https://stackoverflow.com/questions/29131865/xcode-swift-how-do-i-declare-a-variable-constant-with-different-values-depend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!