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

Swiftの返り値ありの関数で処理が1行だけならreturnは要らないらしい

Last updated at Posted at 2020-06-07

はじめに

最近Swiftを始めたが、関数の返り値で納得がいかないところが有ったので
少し検証してみました。
間違っていたら教えてください。

疑問に思ったこと

前提として
Swiftの入門で関数の返り値がありの時はreturnを書かないとエラーが出ると教わった

しかし、swiftUIのチュートリアル中に下記の記載が有った。

func makeUIView(context: Context) -> MKMapView {
    MKMapView(frame: .zero)
}

あれ? おかしいな。返り値が指定されているのにreturnで返してないぞ?

私の思う正しい記載方法はこちらです

func makeUIView(context: Context) -> MKMapView {
    return MKMapView(frame: .zero)
}

最初に思ったこと

ハハーン、これはRubyでやったことあるぞ!
最後の処理の結果を返すやつだな!

ということで検証してみた

1. 関数内に処理なし

func test(str: String) -> String {

}

var str = test(str: "test")
print(str)

結果:エラーが出力された

Missing return in a function expected to return 'String'

2. 関数内に1行だけ処理を書いてみる

func test(str: String) -> String {
    str + "です。"
}

var str = test(str: "test")
print(str)

結果:処理の結果を取得した。

testです。

3. 関数内に2行分処理を書いてみる

func test(str: String) -> String {
    let ret: String
    str + "です。"
}

var str = test(str: "test")
print(str)

結果:エラーが出力された

Missing return in a function expected to return 'String'; did you mean to return the last expression?

4. 関数の最後に値を返したい変数のみ書いてみる

func test(str: String) -> String {
    let ret = str + "です。"
    ret
}

var str = test(str: "test")
print(str)

結果:エラーが出力された

Missing return in a function expected to return 'String'; did you mean to return the last expression?

検証結果から推測

  1. 処理が1行しかない場合は処理結果を返してくれる。
  2. 処理が2行以上ならreturnを付けないとエラーが出る。
  3. rubyとは違い、処理の最後を返してくれるわけではない。

最後に

まだ公式リファレンスにも目を通していないにわかswift使いなんで
先輩方はxxx見たら一発でわかるだろボケ!
と罵ってください。

0
1
3

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?