LoginSignup
10
11

More than 5 years have passed since last update.

WeakキャプチャリストでOptional Chainingするとエラーになった

Last updated at Posted at 2014-09-17

問題

Weakキャプチャリストを記述して循環参照を回避しようとしました。
selfはOptional扱いになるので、クロージャの式でselfをOptional Chainingにするとエラーになりました。

WTDCommentsViewController_swift_—_Edited.jpg

WTDCommentsViewController_swift.jpg

Cannot invoke 'animateWithDuration' with an argument list of type '(NSTimeInterval, delay: FloatLiteralConvertible, options: UIViewAnimationOptions, animations: () -> () -> $T4, completion: (finished: Bool) -> ())'

原因

クロージャは式が1行の場合その式の結果を戻り値として返します。
layoutIfNeededの戻り値はVoidですがselfがnilの場合self?はnilを返します。
animationsクロージャ型の戻り値はVoidですが、式がnilを返却する可能性があるためエラーになっているようです。

解決方法

selfをOptional Bindingにするとコンパイルが通りました。

WTDCommentsViewController_swift.jpg

Optional Chainingで左辺に代入するとコンパイルワーニングが出ますがコンパイルは通りました。

WTDCommentsViewController_swift_—_Edited.jpg

最後にreturnを記述するとコンパイルが通りました。

WTDCommentsViewController_swift.jpg

追記

@mono0926 さんより以下ご指摘頂きました。
ありがとうございます。

式が1つの場合、その式の評価結果が戻り値になってしまうんですよね。
なので、self?.view.layoutIfNeeded()の前に何か他の処理が書かれている場合もコンパイルが通ると思います。

10
11
1

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
10
11