1
3

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.

【Swift】これでワカッタ!なるほど!オプショナル型ってそーゆーこと

Last updated at Posted at 2020-12-08

というわけで

つづき。
前回はこれを見てね。

【Swift】オプショナル型の何が嬉しいのか
https://qiita.com/antk/items/2d780f152c26a3733109

今回はこのオプショナル型を活用してみる。

ラップ

ラップとは?
とりあえず置いといて、前回「nilが使える」ということで定義したオプショナル型。

var hoge: String?

この hoge というオプショナル型の変数そのままではいじることができない
どういうことか?
上記のように文字列型(String)だとわかりにくいので、例えば

var number: Int? = 2

という数値型(Int)のオプショナル型の変数を定義して、こいつに 2 を入れている。例えばこれを出力すると

print(number)

// 出力 Optional(2)

という結果が出る。
逆に、 ? を付けない非オプショナル型だと

var number: Int = 2

print(number)

// 出力 2

さっきの Optional が付いていない、ただの 2 が出力される
非オプショナル型と違い、オプショナル型で定義されているのはただの 2 じゃないのである。
paiza.ioとかで試してみるといい。
これはなんなのかと言うと、 Optional という殻、カプセル、シェルター、バリアー……まあなんでもいいが、オプショナル型は要素がそういうものに入っていると考える。
これを『ラップ(wrap)されている』という。
ラップされている numberに入っているので

var number: Int? = 2

print(number + 4)

// エラー

このように数字を足して 6 にしようとしても Optionatl の殻に弾かれてしまうのでうまくいかないのである。
これをやるには殻を解く、アンラップという作業が必要になる。

アンラップ

オプショナル型変数の後ろに ! を付ける。

var number: Int? = 2

print(number! + 4)

// 出力 6

こうすることで望みの結果が出た。
全然関係ないがデーモン小暮閣下は昔『!(エクスクラメイション)』という名義でアルバムを出していた。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?