LoginSignup
14
15

More than 5 years have passed since last update.

Objective-C で二項演算子 ?: を使う

Last updated at Posted at 2012-08-11

GCC や LLVM の C コンパイラには三項演算子 ?: を独自に拡張した 二項 演算子 ?: がある。 x ?: y のように使い、 x ? x : y とほぼ同様に動作する(ただし前者は x を1回しか評価しないので、 x に副作用がある場合は動作が異なる)。

42 ?: 0; // => 42
0 ?: 42; // => 42
0 ?: 0 ?: 42; // => 42

失敗すると nil を返すメソッドのフォールバック処理が簡単に書ける。

NSString *str = [obj parsedString] ?: defaultStr;

Objective-C で開発する限り LLVM からは離れないのだから積極的に使っている。

14
15
0

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
14
15