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?

More than 1 year has passed since last update.

早期リターン

Last updated at Posted at 2024-01-12

早期リターン(さっさと処理を抜けたい時に使える)

早期リターンを使用しない場合

引数が0の場合でも、処理が続行してしまう。
余計な処理をしている。

func sum(number: Int) -> Int {
    guard number > 0 else {
        // 条件が成り立たない場合、ここで処理を続行する
        print("条件不成立")
    }
    
    // 条件が成り立った場合の処理
    var sum = 0
    
    for i in 1...number {
        sum += i
    }
    
    return sum
}

let result = sum(number: 5)
print(result)  // 出力: 15

早期リターンした場合(guard文を使った例)

number <= 0という条件が成り立つ場合、すぐに0を返して関数を終了しています。
これにより、不要な計算を省略し、コードがより効率的になる。

func sum(number: Int) -> Int {
    guard number > 0 else {
        // 条件が成り立たない場合、早期リターン
        return 0
    }
    var sum = 0
    
    for i in 1...number {
        sum += i
    }
    
    return sum
}

let result = sum(number: 5)
print(result)  // 出力: 15

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?