LoginSignup
10
9

More than 5 years have passed since last update.

そうだ, 三項演算子を使おう.

Last updated at Posted at 2014-06-21

皆さん, 3項演算子使ってますか?使ってますよね. 便利ですよね.

Objective-Cに限った事では無いのですが元々GNU拡張らしいので全部の環境で使えるわけではないですし, Objective-Cで使う事が多いのでObjective-Cネタとして書きます.

Foo foo = bar ? bar : baz;

みたいな書き方が

Foo foo = bar ?: baz;

って書ける. ただそれだけです. ただそれだけなんですが, Objective-Cは基本的に困ったらnil返すって人なので程よく使えます.

例えば,

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if(!cell) CustomCell.loadFromNib;

って書いてたことが

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier] ?: CustomCell.loadFromNib;

って書けちゃう. 便利.

/* tableViewにregisterNibとかしておけばこの例で書いてる事は不要だけどstoryboardとかからIBOutletで接続するのがめんどくさいときとかにはオススメです. */

10
9
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
10
9