2
0

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 3 years have passed since last update.

Objective-Cで三項演算子のYESの場合を省略する

Last updated at Posted at 2020-05-29

背景

案件のコード見てたらすごく簡潔に書かれた三項演算子があった!
まさかこんな書き方ができるとは知らなかったので、メモしておきます。

コード


NSDictionary *dic = @{@"a": @"AAA", @"b": @"BBB"};

NSString *str = dic[@"b"] ? : @"";
NSLOG(@"str: %@", str);
// str: BBB

str = dic[@"c"] ? : @"";
NSLOG(@"str: %@", str);
// str: 

Swift だったら...

Swiftならデフォルト値入れるだけで🙆‍♀️
Swift便利だな〜

let dic = ["a": "AAA", "b": "BBB"]
var str = dic["b"] ?? ""
// str : BBB
print("str : \(str)")

str = dic["c"] ?? ""
print("str : \(str)")
// str :

まとめ

Objective-Cでは三項演算子の第2項は省略できる👍
Swiftはデフォルト値入れるだけで、nilの場合の値が決めれる👍

参考

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?