LoginSignup
196
185

More than 5 years have passed since last update.

Swift での #ifdef DEBUG のやり方

Last updated at Posted at 2014-09-13

これまで Objective-C で開発をしていたとき、デバッグ時のみ実行したいコードは以下のように記述していました。

#ifdef DEBUG
    // ...
#endif

しかし Swift では同じ記述ができません。
Apple のドキュメントによると、代わりに以下のように記述できるとあります。

#if build_configuration
    // ...
#elseif build_configuration
    // ...
#else
    // ...
#endif

試しに #if DEBUG ... と書いてみましたが期待した動作をしません。
Apple のドキュメントをよく読むと以下のように書いてあります。

Swift code and Objective-C code are conditionally compiled in different ways. Swift code can be conditionally compiled based on the evaluation of build configurations. Build configurations include the literal true and false values, command line flags, and the platform-testing functions listed in the table below. You can specify command line flags using -D <#flag#>.

どうやらコンパイル時のオプションで -D flag と指定するようですね。
Xcode の Build Settings を見てみると、Swift Compiler - Custom Flags に Other Swift Flags という項目があります。
ここに -D DEBUG という定義を追加してみたところ、先ほどのコードは無事動作しました。
(まだ Xcode 6 は GM なのでスクリーンショットを貼り付けられないのが残念)

[追記 2014.09.21] Xcode 6 が正式にリリースされたのでスクリーンショットを貼り付けました。

swift_compiler-custom_flags-xcode601.png

プロジェクトを新規作成すると Preprocessor Macros にはこれまで通り DEBUG=1 の定義がされているのですが、Other Swift Flags は空っぽです。
Xcode 6 リリース時には最初から -D DEBUG が定義済みとなっていると良いですね。

[追記 2014.09.21] Xcode 6 が正式リリースされたので確認しましたが、残念ながら beta、GM のときと同様空っぽでした。残念。

参考

196
185
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
196
185