Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

3
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 5 years have passed since last update.

戻り値のある関数・メソッド内でguard文を使う

Posted at

戻り値のある関数やメソッド内で定義したguard文に戻り値を設定しないと、コンパイルエラーが起きてしまいます…。

var num:Int?

func numFunc() -> Int {
    
    num = 123
    
	guard let num_ = num else { return } // コンパイルエラーが起きる
    
    return num_
}
print(numFunc())

これを回避するには、**”guard文でその関数・メソッドの戻り値の型の空要素を返す”**ことで回避することができます!

var num:Int?

func numFunc() -> Int {
    
    num = 123
    
    guard let num_ = num else { return 0 } // 戻り値の型の空要素を返す
    
    return num_
}
print(numFunc())
3
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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

3
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?