LoginSignup
13
12

More than 5 years have passed since last update.

swiftで if let を使う理由 (のひとつ )

Last updated at Posted at 2015-07-11

swiftでnull(nil)チェックを行う際に、下記のようにしてチェックをする事が多いと思います。

hoge.swift
if let hoge = nilValue {
    //nilじゃなかったらー
}

この場合、nilValueがnilじゃなかったら中に入るのはわかるのですが、別に下記のように普通にnullチェックしてもいいんじゃあないかって初心者の僕は思うんですよね

fuge.swift
if nilValue != nil {
    //nilじゃなかったらー
}

上記の2つとも動作的には同じ(たぶん)なはずなので、わざわざわかりにくい if let の方を使う必要ってなんなんだろうなって思ってたんですが、下記のように、ifの中でnullチェックしたものを使う場合に便利なんですよね。

poge.swift
if let poge = controller.navigationController {
    poge.hidesBarsOnSwipe = true
    poge.hidesBarsOnTap = true
    poge.navigationBarHidden = false
    poge.popToRootViewControllerAnimated(true)
}

上記を if let なしで書くと、下記のようになります。

pupi.swift
controller.navigationController?.hidesBarsOnSwipe = true
controller.navigationController?.hidesBarsOnTap = true
controller.navigationController?.navigationBarHidden = false
controller.navigationController?.popToRootViewControllerAnimated(true)

もちろんこれでも動作はするのですが、4度のアンラップ(?)を行ってしまっています。さらに、controller.navigationControllerを何度も書かなくて済みます。

【まとめ】
if let を使う理由は、nullチェックを行った変数をifの中で使用する際に便利だからです。

※説明が間違っている場合や他にも理由がある場合は教えていただけると助かります。

参考
Swift Optionals: When to use if let, when ? and !, when as? and as
http://www.touch-code-magazine.com/swift-optionals-use-let/

13
12
4

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
13
12