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.

クロージャ

Posted at

クロージャ

クロージャは、処理をまとめて呼び出し可能にします。処理を即席的に定義して他の処理に渡すことができます。書き方はこんな感じ。

{ 引数 in 戻り値を返す値 }

引数には入力される値、戻り値には出力される値を入れます。

例として、mapメソッドに各要素を2倍にするクロージャ式を渡す処理が下記となります。

let num = [1, 2, 3]
let doubleNum = num.map({ value in value * 2 })
print(doubleNum) // [2, 4, 6]

まとめ

クロージャは関数の一種ですが、名前も要らず、型推論により型の記述が省略可能だったりと、関数よりも軽量化して定義することができるメリットがあります。

参考

[増補改訂第3版]Swift実践入門 ── 直感的な文法と安全性を兼ね備えた言語 (WEB+DB PRESS plusシリーズ)

0
1
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
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?