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.

クロージャについてのメモ

Last updated at Posted at 2021-11-17

クロージャ

クロージャを宣言しても呼び出しがあるまでは中身のコードは処理されない。

●基本記法

let closure = { (x: Int) -> String in
            String(x) + "あいうえお"
}
let str = closure(6)
// print: 6あいうえお

複数行の場合
let closure2 = { (x: String) -> NSDecimalNumber in
            let deciX = NSDecimalNumber.init(string: x)
            let deciY: NSDecimalNumber = 123
            return deciX.multiplying(by: deciY)
}
let decimal = closure2("10")
// print: 1230

他の記法

/* 引数と戻り値の省略 */
// 先に宣言する
let closure3: (Int) -> Double

// aaa はクロージャ内で使う引数的な存在(?)。今回ではIntにあたる
closure3 = { aaa in
            Double(aaa)
}
let double = closure3(22)
// print: 22.0

funcの引数にも使えるそうだけれどまだ試してないのでサンプルコードない。
使い方がわからないものは書けない。

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?