12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-C 三項演算子の活用

Posted at

三項演算子(条件演算子)使ってますか?
可読性が落ちたり向上したりと使いどころを考える必要がありますが、個人的には結構好きで使ってます。

三項演算子とは

<条件式> ? <真式> : <偽式>

if文で書くと…

if (<条件式>) {
	<真式>
} else {
	<偽式>
}

よく使う例

初期化とか

// 大きい値の方がsizeに入る
CGFloat size = width < height ? height : width;

NSLog内とか

BOOL selected = YES;
NSLog(@"状態は? %@", selected ? @"選択されている" : @"選択されていない");

メソッドとか

- (void)setHidden:(BOOL)hidden animated:(BOOL)animated
{
	// durationが0だとアニメーションにならない
    [UIView animateWithDuration:animated ? 0.3f : 0.f animations:^{
        self.alpha = !hidden;
    }];
}

使いどころによっては、簡潔に書けるかと思います。

12
10
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?