- Mastering macOS Programming
- Stuart Grimshaw
- 259字
- 2021-07-02 22:54:25
Using custom flags in code
Once upon a time, in the Days Before Swift, there was a language called C, and it had something called preprocessor directives, and they were used and abused for all sorts of things. In Objective C, these directives could test for a value present in the build settings, and Swift does the same thing, except that the preprocessor directives have been renamed compiler control statements.
During development, we're going to save ourselves some typing by prepopulating the app's Rate and Pre-Tax Price text fields with some arbitrary values.
Navigate to ViewController.swift, and add the following code to its viewDidLoad method:
#if DEV
rateTextField.stringValue = "16"
preTaxTextField.stringValue = "144"
#else
// possibly something else
#endif
Here we see Swift's compiler control statements in action (we included the empty #else statement for the sake of completeness).
And that's all you need to do. If the compiler can't find Dev defined in the build settings, it will ignore the code in the #if block and the app will build as if it didn't exist. So, when you select the Release scheme for external testing, App Store, or enterprise distribution, the text fields will be empty, as they should be. But when we're in the Dev scheme, we won't need to repeatedly enter text into those fields.