Help us understand the problem. What is going on with this article?

【Swift】"??"を有効活用しよう - Nil Coalescing Operator -

More than 3 years have passed since last update.

Bondのソースコードを眺めていたら??(ダブルクエッションマーク)が目に入り、頭も??になりました。BondオリジナルのSugar Sytaxかと思いきや、実はこれSwiftオリジナルのオペレーターで、Nil Coalescing Operatorと呼ぶことがわかりました。

簡単な例

使い方はいたってシンプル。
Optionalに対して、a != nil ? b! : cを評価し、aがnilでなければbを強制アンラップし、aがnilであればcを返します。

var maybeInts: [Int]? // nil
maybeInts != nil ? maybeInts! : [] // []
maybeInts ?? [] // []

もしintが入ったらこうなる。

maybeInts = [10,20,30]
maybeInts ?? [] // [10,20,30]
maybeInts != nil ? maybeInts! : [] // [10,20,30]

注意すべき点は型を揃える必要があるところです。

maybeInts = [10,20,30]
let wrong = maybeInts ?? [10.0] // error
let correct = maybeInts ?? [1,2,3] // ok

実際の使いどころ

一つの例としてオプショナル型配列と使うと、かなりすっきりします。

Before
if let maybeInts = maybeInts {
    for x in maybeInts  {
        let doubled = x * 2
        print(doubled)
    }
}
After
for x in maybeInts ?? [] {
    let doubled = x * 2
    print(doubled)
}

これなら早速、明日からでも使えますね。

参考

The Swift Programming Language (Swift 2.2)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした