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 1 year has passed since last update.

【Swift】オプショナルバインディング-改めて整理

Posted at

目次

1.オプショナルバインディングとは?
2.シャドーイング
3.実例
4.終わりに

1. オプショナルバインディングとは?

Swiftでは厄介なことにnillを意識しないと、アプリがクラッシュしてしまったりと意図しないシステムエラーが起きてしまいます。(逆にこのことを利用する開発手法もありますが、、)
そんな、オプショナル型をアンラップする正当な手法のひとつがオプショナルバインディングです

2. シャドーイング

if let ~guard let ~の2つの記法で記述する方法をシャードーイングと言います。

3. 実例

  • if let~ 構文
IF-Let構文
let a: Int? = 1

if let a = a {
    // アンラップ対象がnillでないときの処理
    print("aはnillではないです!")
} else {
    // アンラップ対象がnillのときの処理
    print("Error- aはnillです")
}

print(type(of: a))

出力結果: Optional Int

  • Guard let構文

Tip
現場ではこちらを多用している印象です!

Guard let構文
let a: Int? = 1

guard let a = a else {
    // アンラップ対象がnillのときの処理
    print("Error- aはnillです")
} 

print(type(of: a))

出力結果: Int
つまり、Guard-Let構文を通過した変数はnillでなくなっているんです。

4. 終わりに

If-Let構文とGuard-Let構文の違いはその記述方法と、これらの処理通過後の変数の型です。
開発現場では、ややGuard-Let構文に軍配が上がっていますが、お好みで。

今回も本記事を最後まで読んでいただいてありがとうございました。
目指せ脱初学者で頑張っていきましょう〜♪

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?