1
2

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.

guard文による分岐処理

Posted at

guard文とは

guard文とは条件が不成立の場合に処理を抜けるための条件分岐文。
条件が不成立の場合は、else節内の処理が実行されguard文を含むスコープから抜けないとコンパイルエラーとなる。

let str = "abc"

func exampleFunction() {
    guard str == "abc" else {
        return  // スコープを抜ける
    }
    
    print(str)
}

guard-let文

guard文もif-let文と同様、guard-let文を利用してオプショナル変数のアンラップが行える。
guard文は条件式が成立しなかった場合にはスコープから抜けるため、guard-let文で宣言された変数や定数はguard-let文以降でも利用可能。

let int: Int? = 123

func exampleFunction() {
    guard let a = int else {
        return
    }
    
    // guard-let文で宣言した定数aを{}の外からも利用できる
    print(a)  // 123
}

if文との使い分け

条件を満たさない場合に処理を早期退出したいときは、if文に比べてguard文の方がシンプルに実装できるため適していると言える。
また、guard文は条件を満たさない場合に必ずスコープを抜けなくてはならないので、想定外の状況においても処理を抜ける実装の漏れを防ぐことができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?