43
41

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.

Swift の ?? ってなんだっけ

Last updated at Posted at 2015-02-25

Xcode6.3 beta2 のリリースノートを見たら、こんなことができるようになるみたいでした。

var allowEmpty = true
var items:[Int]? = [ 0, 1, 2 ]
var emptyItems:[Int]? = [Int]()
if allowEmpty || items?.count ?? 0 > 0 {
    println("do this")
}
if allowEmpty || emptyItems?.count ?? 0 > 0 {
    println("do this") // not executed
}

?? は三項演算子を簡単に書けるようにしたような感じ。
?? は変数がnilかどうかの分岐を簡単に書けるようにしたような感じ。
(a != nil) ? a! : ba ?? b で書ける。

Swift本の Nil Coalescing Operator という項で説明されていますね。

この場合これでもいけます。

var allowEmpty = true
var items:[Int]? = [ 0, 1, 2 ]
var emptyItems:[Int]? = [Int]()
if allowEmpty, let i = items where i.count > 0 {
    println("do this")
}
if allowEmpty, let i = emptyItems where i.count > 0 {
    println("do this") // not executed
}

43
41
5

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
43
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?