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

Basic Operators - Nil-Coalescing Operator

Last updated at Posted at 2017-03-04

Nil合体演算子 Nil-Coalescing operator は、 (a ?? b) という構成で成り立っている。

読み方は、「オプショナル a が値を持っている場合は a の値を返し、もし a が nil ならば b の値を返す」となる。

利用の条件としては、

  • a は必ずオプショナル型でなければいけない。
  • b の値は a が持つ値の型と同じでなければいけない。

nil合体演算子は 三項演算子 でも表せる。

a != nil ? a! : b

上記例では a! と強制アンラップしているが、 a! が対象となるのは値が nil ではない場合のみなので、問題は生じない。

仕様で、もし a の値が nil ではなかった場合、b の値は一切考慮されない。

使用例

// 基本文法での b にあたる
let defaultColorName = "red"

// 基本文法での a にあたる
// 初期値がないので値は nil
var userDefinedColorName: String?

// nil合体演算子で判断している。 userDefinedColorName は nil なので、 defaultColorName の "red" が返される。
var colorNameToUse = userDefinedColorName ?? defaultColorName

// 値格納
userDefinedColorName = "green"

// userDefinedColorName に値があるので、それ、今回は "green" が返される。
colorNameToUse = userDefinedColorName ?? defaultColorName
0
0
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
0
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?