使用 Swift 区分两个 Xcode 目标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27283845/
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
Differentiate between two Xcode targets with Swift
提问by Jo?o Cola?o
How can I differentiate between two Xcode targets with Swift? The idea is to make a free and a paid version of an app with the same code base in Xcode.
如何使用 Swift 区分两个 Xcode 目标?这个想法是在 Xcode 中使用相同的代码库制作一个免费和付费版本的应用程序。
With objective C I could use preprocessor macros but with Swift those are unavailable.
使用客观 CI 可以使用预处理器宏,但使用 Swift 则不可用。
采纳答案by Jo?o Cola?o
Since Xcode 8 you can set the compilation conditions in the Build Settings for each target under Active Compilation Conditions.
从 Xcode 8 开始,您可以在Active Compilation Conditions下的每个目标的 Build Settings 中设置编译条件。
With those set you can use:
使用这些设置,您可以使用:
#if FREE
//do something
#endif
For more details see the i40west answerand comments.
有关更多详细信息,请参阅i40west 答案和评论。
回答by i40west
In Xcode, go into the build configuration for a target. Find the section called Swift Compiler - Custom Flags, which contains a setting called Other Swift Flags.
在 Xcode 中,进入目标的构建配置。找到名为Swift Compiler-Custom Flags 的部分,其中包含名为Other Swift Flags的设置。
Add a command-line flag for the compiler to add a flag, pretty much just like you'd do with the C compiler.
为编译器添加一个命令行标志以添加一个标志,就像您对 C 编译器所做的一样。
Now you've got -D Something
being passed to the Swift compiler. In your Swift code, you can now do this:
现在你已经-D Something
被传递给 Swift 编译器。在您的 Swift 代码中,您现在可以执行以下操作:
#if Something
let foo = "bar"
#endif
It looks a lot like the C preprocessor, but unlike C, all code in all conditional sections has to be syntactically correct or the program won't compile. So, you can set a flag on each target in the build settings and use them in your code.
它看起来很像 C 预处理器,但与 C 不同的是,所有条件部分中的所有代码都必须在语法上正确,否则程序将无法编译。因此,您可以在构建设置中的每个目标上设置一个标志,并在您的代码中使用它们。
回答by Micha? Ziobro
One way is to add Flags to target and use preprocessor. But the other way I think would be to use something like this
一种方法是向目标添加标志并使用预处理器。但我认为的另一种方式是使用这样的东西
if Bundle.appTarget == "" { } else { }
extension Bundle {
public static var appVersion: String? {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
public static var appBuild: String? {
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String
}
public static func _version() -> String {
let dictionary = Bundle.main.infoDictionary!
let version = dictionary["CFBundleShortVersionString"] as! String
let build = dictionary["CFBundleVersion"] as! String
return "\(version) build \(build)"
}
public static var appTarget: String? {
if let targetName = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String {
return targetName
}
return nil
}
}