以下swiftのクロージャーついての質問です。

1 UIView.animateWithDuration(
2 duration, animations: { () -> Void in sender.transform = transform}) {
3 (Bool) -> Void in UIView.animateWithDuration(
4 duration, animations: { () -> Void in sender.transform = CGAffineTransformIdentity }) {
6 (Bool) -> Void in }
7 }

1行目はクラスメソッドを実行しているかと思います。UIView.animateWithDuration
2行目はクロージャーを実行していると思いますが、末尾の{は、その直前でクラスメソッドの閉じ括弧”)”があるので、末尾の{がよくわかりません。。
{がクラスメソッドのあとに、突然でてきたように思えるのです。
どういう意味になりますでしょうか。。

回答の条件
  • 1人1回まで
  • 登録:
  • 終了:2015/05/19 23:45:03
※ 有料アンケート・ポイント付き質問機能は2023年2月28日に終了しました。

回答1件)

id:a-kuma3 No.1

回答回数4974ベストアンサー獲得回数2154

ポイント100pt

呼び出しているのは、animateWithDuration:animations:completion: 。
引数を三つ取るのを呼び出しています。
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/clm/UIView/animateWithDuration:animations:completion:

class func animateWithDuration(_ duration: NSTimeInterval,
                    animations animations: () -> Void,
                    completion completion: ((Bool) -> Void)?)

「末尾の{は、その直前でクラスメソッドの閉じ括弧”)”があるので、末尾の{がよくわかりません。。」の末尾の { から 次の } までが第3引数の completion のクロージャにあたります。
クロージャが二重になっているので、更に分かりにくくなっていますが、以下と同じコードです。

UIView.animateWithDuration(
    duration,
    { () -> Void in sender.transform = transform},
    { (Bool) -> Void in ...}        // メソッドの閉じ括弧の外に出ていた部分が、第3引数の completion
    )
{

Trailing Closures と言うそうです。

Trailing Closures(後置記法)

関数の最後の引数は()の外に出す事ができる
{} ブロック内が長い場合など便利
 

http://qiita.com/kiyotaman/items/55966cc10ef2ed44c4fd#3-6

いろいろな書き方があるクロージャを、sort を呼び出すサンプルがならべてあるので、分かりやすいと思います。

// sort のインターフェース
// sort(Array, (String, String) -> Bool)

// 一般的な書き方
reversed = sort(names, { (s1: String, s2: String) -> Bool in
    return s1 > s2
    })

// Inferring Type From Context(型の推論)
reversed = sort(names, { s1, s2 in return s1 > s2 } )

// Shorthand Argument Names(簡易引数名)
reversed = sort(names, { $0 > $1 } )

// Trailing Closures(後置記法)
reversed = sort(names) { $0 > $1 }

# Ruby のブロックに似てる

id:yayayai

なるほど。ありがとうございます!

2015/05/16 11:20:16

コメントはまだありません

この質問への反応(ブックマークコメント)

「あの人に答えてほしい」「この質問はあの人が答えられそう」というときに、回答リクエストを送ってみてましょう。

これ以上回答リクエストを送信することはできません。制限について

回答リクエストを送信したユーザーはいません