人力検索はてな
モバイル版を表示しています。PC版はこちら
i-mobile

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


●質問者: FujiiRock
●カテゴリ:コンピュータ ウェブ制作
○ 状態 :終了
└ 回答数 : 1/1件

▽最新の回答へ

1 ● a-kuma3
●100ポイント

呼び出しているのは、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 のブロックに似てる


FujiiRockさんのコメント
なるほど。ありがとうございます!
関連質問

●質問をもっと探す●



0.人力検索はてなトップ
8.このページを友達に紹介
9.このページの先頭へ
対応機種一覧
お問い合わせ
ヘルプ/お知らせ
ログイン
無料ユーザー登録
はてなトップ