LoginSignup
4

More than 5 years have passed since last update.

Implicitly unwrapped optionalsについて調べてみた

Last updated at Posted at 2014-09-15

optional valueを宣言するときは?を使うのだが、!を使っているのを見かけたので調べた。
Appleのドキュメント"Implicitly unwrapped optionals"に説明があった。
型の後ろに!が付くと、暗黙のunwrapped optionalになる。

var wrappedString: String? = "0"

wrappedString?.toInt()

上のwrappedStringはwrapされているoptional value。
wrapされている場合、利用するときに末尾に?か!を付けなければならない。

値が必ず入っている場合、毎回?か!をつけるのは面倒なので、暗黙のunwrapped optionalを使うことができる。

var wrappedString: String? = "0"
var unwrappedString: String! = wrappedString

unwrappedString.toInt()

unwrappedStringには?を付けなくてもアクセスできる。

もしnilが入っている場合、ランタイムエラーが発生する。

var wrappedString: String? = nil
var unwrappedString: String! = wrappedString

unwrappedString.toInt() //Runtime error

ドキュメントには、Implicitly unwrapped optionalsは、nilになる可能性がある変数には使うなと書いてある。
また、nilチェックが必要になるなら普通のoptionalを使えと書いてある。
あまり積極的には使わないほうが良さそう。

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
4