この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
検証環境
本エントリは以下の環境で検証を行っています。
- macOS Sierra バージョン 10.12.6
- Xcode Version 9.2 (9C40b)
- Swift 4
Xcode 8.0から「Active Compilation Conditions」が追加された
Xcode 7までは以下の記事のように、Preprocessor MacrosとOther Swift Flagsを設定することで#if, #elseif, #else ,#endif
による分岐を行っていました。
Xcode 8.0からは「Active Compilation Conditions」という設定項目が追加されていて、より設定が簡単になっています。
以下は、Xcode 8.0リリースノートに記載されている当該設定の説明です。
Active Compilation Conditions is a new build setting for passing conditional compilation flags to the Swift compiler. Each element of the value of this setting passes to swiftc prefixed with -D, in the same way that elements of Preprocessor Macros pass to clang with the same prefix. (22457329)
設定方法
XcodeのProject navigatorでプロジェクトを選択するとPROJECTとTARGETSが表示されるのでPROJECTを選択し、active compilation conditions
で検索すると
設定が表示されるのでビルドコンフィギュレーション毎に条件を設定します。
デフォルトではDebugビルドの時には「DEBUG」が設定されていますね。
Active Compilation Conditions を設定することで以下のような分岐が可能になります。
#if DEBUG
// DEBUGが定義されている場合の処理
#else
// DEBUGが定義されていない場合の処理
#endif
お試しください。