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?

Swiftのオプショナル型とアンラップ

Last updated at Posted at 2024-08-02

はじめに

いつもノートに書き殴って勉強してるアナログ人間なんですがちょっと暇な時間ができたので記事書きながら勉強してみました🙌
プログラミング初心者すぎてごめんな奴が書いたので間違ってること書いてたら批判コメントで教えてください。

Optional(オプショナル)型とは

一応swiftのドキュメント
You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value of a specified type, and you can unwrap the optional to access that value, or there isn’t a value at all.
値が存在しない可能性がある状況では、オプションを使用します。オプションは 2 つの可能性を表します。指定された型の値が存在し、オプションをラップ解除してその値にアクセスできるか、または値がまったく存在しないかのいずれかです。

ドキュメントの通りだけれど

  • オプショナル型 => 変数に通常の値、もしくはnil(空)が格納できる。
  • 非オプショナル型 => 変数に通常の値が格納できる。

swiftのオプショナル型は型の一つなので例えばIntInt? は別の型。
Int?Intと同じように扱うためにはアンラップする必要がある。

Unwrap(アンラップ)

unwrapはwrap(包む)の対義語
Optional("値 or nil") を 値 or nil にする作業です。
「オプショナル型はnil包めちゃう〜からnilも格納できる!でも通常の値も包んじゃうの(>_<)だからアンラップしてネ」 ってイメージで私は考えることにします。

調べたところアンラップには3+1種類あるらしい
↓私が調べた勝手なイメージです

  • ノリで使えない=>実行時nilでないことを保証できる場合のみ使用する(nilの場合対策してなかったらクラッシュしちゃうことがあるよん)
  • ノリで使える=>nilでもオッケー🙆
    018993C9-1F05-49C2-82E8-605DE056CC6E.JPEG

①暗黙的アンラップ

オプショナル型の変数が使われるタイミングで自動的にアンラップされる。
最初はnilであっても後で必ず値が設定されることが保証されている場合に使う。
書き方: 変数の宣言時に型の後ろに ! をつける。

var implicitlyUnwrappedOptional: String! = "Hello, World!"

func printImplicitlyUnwrappedOptional() {
    // 暗黙的アンラップは自動的にアンラップされる
    print(implicitlyUnwrappedOptional)
}

printImplicitlyUnwrappedOptional() // 出力: Hello, World!

②強制的アンラップ

オプショナル型の変数を強制的にアンラップして値を取り出す方法。オプショナル型の変数がnilではないことが確実な場合に使用する。ただ、nilだったときやばいやばいΣ੧(❛□❛✿)
書き方: オプショナル型の変数から値を取り出すときに、変数名の後ろに ! をつける

var forcedUnwrappedOptional: String? = "Hello, Swift!"

func printForcedUnwrappedOptional() {
    // 強制的アンラップは感嘆符 `!` を使用
    print(forcedUnwrappedOptional!)
}

printForcedUnwrappedOptional() // 出力: Hello, Swift!

③オプショナルバイディング

オプショナル型の変数がnilかどうかをチェックし、nilでなければその値を一時的に非オプショナル型の変数として使用する方法。これにより、安全にアンラップされた値を利用できる。
書き方: if let または guard let を使う。

  • if let => nilだったとき違う処理したい場合
  • guard let => nilだったとき止めちゃう場合(エラーとして扱うとかとか)
var optionalBindingExample: String? = "Hello, Optional Binding!"

func printOptionalBinding() {
    // オプショナルバインディングを使用して安全にアンラップ
    if let unwrapped = optionalBindingExample {
        print(unwrapped)
    } else {
        print("Value is nil")
    }
}

printOptionalBinding() // 出力: Hello, Optional Binding!

var optionalBindingExample: String? = "Hello, Optional Binding!"

func printOptionalBinding() {
    // guard letを使用して安全にアンラップ
    guard let unwrapped = optionalBindingExample else {
        print("Value is nil")
        return
    }
    print(unwrapped)
}

printOptionalBinding() // 出力: Hello, Optional Binding!

④オプショナルチェイニング(カタカナちょっとダサい)

アンラップではないってどこかの記事に書かれてた。けどやってることは似てるよね。
オプショナル型の変数に対して複数のプロパティやメソッドを安全に呼び出す方法。途中でnilが発生した場合、それ以降は無視され、全体の結果がnilとなる。
書き方: オプショナル型の変数のプロパティやメソッドを呼び出すときに、変数名の後ろに ? をつける

struct Address {
    var street: String?
}

struct User {
    var name: String
    var address: Address?
}

let userWithAddress = User(name: "Alice", address: Address(street: "123 Main St"))
let userWithoutAddress = User(name: "Bob", address: nil)

func printStreet(user: User) {
    // オプショナルチェイニングを使用してプロパティにアクセス
    if let street = user.address?.street {
        print(street)
    } else {
        print("Street is nil")
    }
}

printStreet(user: userWithAddress) // 出力: 123 Main St
printStreet(user: userWithoutAddress) // 出力: Street is nil

⬇️読んだ記事
https://qiita.com/YusukeHosonuma/items/f6b1e9320e375e678da9

他には ??演算子(Nil-Coalescing Operator) とかがあるけれど三項演算子にアンラップ機能ついたって感じなので説明不要だと思います。
書きながら勉強したらめっちゃ頭に入るから良いですね
でも無駄に時間かかるからたまーーーーにこのやり方で勉強することにするか〜〜〜( ・∇・)

良きプログラミングライフを🤚

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?