Swift
Preprocessor Flags
API Keys
Debugging
Conditional Compilation

Swift how to use PREPROCESSOR Flags like if DEBUG to implement API keys?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In Swift, use #if DEBUG to conditionally compile code for different build configurations. This is commonly used to switch between development and production API keys, base URLs, and logging levels. Unlike C preprocessor macros, Swift compilation conditions are checked by the compiler and do not perform text substitution. Define custom flags in Xcode under Build Settings > Swift Compiler > Active Compilation Conditions, or pass -D FLAG_NAME to swiftc. The DEBUG flag is predefined for debug builds in Xcode projects.

Basic #if DEBUG Usage

swift
1struct APIConfig {
2    static let baseURL: String = {
3        #if DEBUG
4        return "https://api-dev.example.com"
5        #else
6        return "https://api.example.com"
7        #endif
8    }()
9
10    static let apiKey: String = {
11        #if DEBUG
12        return "dev_key_abc123"
13        #else
14        return "prod_key_xyz789"
15        #endif
16    }()
17}
18
19// Usage
20let url = URL(string: "\(APIConfig.baseURL)/users")!

Code inside the inactive branch is not compiled at all — it does not add to your binary size or affect runtime performance.

Setting Up Custom Flags in Xcode

  1. Select your target in Xcode
  2. Go to Build Settings
  3. Search for "Active Compilation Conditions"
  4. Add flags per configuration:
    • Debug: DEBUG
    • Release: RELEASE
    • Custom: STAGING, BETA, etc.
swift
1// Using custom flags
2#if DEBUG
3let environment = "Development"
4#elseif STAGING
5let environment = "Staging"
6#else
7let environment = "Production"
8#endif

In your Package.swift (for SPM):

swift
1.target(
2    name: "MyApp",
3    swiftSettings: [
4        .define("STAGING", .when(configuration: .debug))
5    ]
6)

Secure API Key Management

swift
1// Option 1: Configuration file not tracked in git
2// Create a file: Secrets.swift (add to .gitignore)
3enum Secrets {
4    static let apiKey = "your_actual_api_key"
5    static let stripeKey = "sk_live_..."
6}
7
8// Option 2: xcconfig files per environment
9// Debug.xcconfig
10// API_KEY = dev_key_abc123
11// BASE_URL = https:$(/)$(/)api-dev.example.com
12
13// Release.xcconfig
14// API_KEY = prod_key_xyz789
15// BASE_URL = https:$(/)$(/)api.example.com
16
17// Info.plist: add $(API_KEY) as a value
18// Read in code:
19struct Config {
20    static let apiKey: String = {
21        guard let key = Bundle.main.infoDictionary?["API_KEY"] as? String else {
22            fatalError("API_KEY not found in Info.plist")
23        }
24        return key
25    }()
26}
 
1# Development.xcconfig
2API_BASE_URL = https:$(/)$(/)api-dev.example.com
3API_KEY = dev_abc123
4ANALYTICS_ENABLED = NO
5
6# Production.xcconfig
7API_BASE_URL = https:$(/)$(/)api.example.com
8API_KEY = prod_xyz789
9ANALYTICS_ENABLED = YES
swift
1// Info.plist entries
2// APIBaseURL = $(API_BASE_URL)
3// APIKey = $(API_KEY)
4// AnalyticsEnabled = $(ANALYTICS_ENABLED)
5
6enum Environment {
7    private static func string(for key: String) -> String {
8        guard let value = Bundle.main.infoDictionary?[key] as? String else {
9            fatalError("\(key) not found in Info.plist")
10        }
11        return value
12    }
13
14    static let baseURL = string(for: "APIBaseURL")
15    static let apiKey = string(for: "APIKey")
16    static let analyticsEnabled = string(for: "AnalyticsEnabled") == "YES"
17}

Logging with Conditional Compilation

swift
1func debugLog(_ message: @autoclosure () -> String, file: String = #file, line: Int = #line) {
2    #if DEBUG
3    let filename = (file as NSString).lastPathComponent
4    print("[\(filename):\(line)] \(message())")
5    #endif
6}
7
8// Usage — the message closure is never evaluated in release
9debugLog("Loaded \(users.count) users")  // Only prints in DEBUG

OS and Platform Checks

swift
1// Combine with platform checks
2#if DEBUG && os(iOS)
3import UIKit
4let isSimulator: Bool = {
5    #if targetEnvironment(simulator)
6    return true
7    #else
8    return false
9    #endif
10}()
11#endif
12
13// Available platform conditions:
14// os(macOS), os(iOS), os(watchOS), os(tvOS), os(Linux)
15// arch(x86_64), arch(arm64)
16// targetEnvironment(simulator)
17// canImport(UIKit), canImport(SwiftUI)

Common Pitfalls

  • Hardcoding API keys directly in source files tracked by git: Even with #if DEBUG, both keys exist in your source code. If the repository is public or compromised, production keys are exposed. Use .xcconfig files or a Secrets.swift file added to .gitignore to keep keys out of version control.
  • Assuming DEBUG is always defined: DEBUG is only predefined in Xcode debug configurations. If you create a custom build configuration or use SPM without explicit settings, DEBUG may not be set. Always verify your build settings include the flag, or define it explicitly in Active Compilation Conditions.
  • Using #if for runtime branching instead of compile-time: #if DEBUG is evaluated at compile time — the inactive branch is completely excluded from the binary. Do not confuse this with runtime checks like if isDebug { }. If you need runtime configuration switching (e.g., a settings toggle), use a regular variable instead of a compilation condition.
  • Escaping URLs in xcconfig files: xcconfig files treat // as a comment delimiter. URLs like https://api.example.com are truncated at //. Use https:$(/)$(/)api.example.com to escape the slashes, or store only the domain and construct the URL in code.
  • Not securing keys in CI/CD pipelines: Even with .gitignore, CI/CD systems need access to production keys. Store them as encrypted environment variables or secrets (GitHub Secrets, Xcode Cloud Environment Variables) and inject them during the build process, not in committed files.

Summary

  • Use #if DEBUG / #else / #endif to switch between development and production API keys at compile time
  • Define custom flags in Xcode Build Settings > Active Compilation Conditions
  • Use .xcconfig files per environment for scalable, git-friendly configuration management
  • Never commit production API keys to source control — use .gitignore, xcconfig files, or CI/CD secrets
  • Remember that #if is compile-time only — the inactive branch is not included in the binary

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design