0
1

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.

条件分岐 ? :  の使い方

Posted at

はじめに

この書き方を見た時に、こんな書き方もあるんや!って思ったが、
この書き方を調べてもわからなかった(?:と調べてもわからなかった)ので、自分なりに一旦まとめていこうと思います。
色々わかり次第、情報を追加していこうと思います。

使われ方

条件式 ? 式か値① : 式か値②
説明すると、条件式がtrueなら?の後ろの①、falseなら:の後の②を実行すると言うもの。

試してみた

switchを用意してisOnがtrueの時とfalseの時を比較して見た。

let switch1 = UISwitch()
let switch2 = UISwitch()

switch1.isOn = true
let number1 = 1 * (switch1.isOn ? 1 : -1)   //1 * 1が実行され、number1 = 1

switch2.isOn = false
let number2 = 1 * (switch2.isOn ? 1 : -1)   //1 * -1が実行され、number2 = -1

このように、trueの時に?の後が実行され、falseの時には:の後の処理が行われる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?