3

Here I have a simple snippet to use simple animation with my defined UIView.

UIView.animateWithDuration(0.1) { [weak self] in

    self?.popOverView.center = gesture.locationInView(self?.view)
}

Here [weak self] is to avoid reference cycle,and I also use trailing closure to simply the code.Howerver,the compiler is unhappy with that and gives me the wrong message.

Cannot invoke 'animateWithDuration' with an argument list of type '(FloatLiteralConvertible, () -> () -> $T2)'

What does $T2 stands for ? And the strange thing is that when there is two or more statements in the closure body, it compiles correctly.

UIView.animateWithDuration(0.1) { [weak self] in
    println()
    self?.popOverView.center = gesture.locationInView(self?.view)
}

And I know that if there is only one statement in the closure body, it is automatically returned.

1 Answer 1

5

Single statement body in a closure have implicit return, so what happens is that the compiler tries to set the result of this statement:

self?.popOverView.center = gesture.locationInView(self?.view)

as the return value. You can fix that by adding an explicit return

self?.popOverView.center = gesture.locationInView(self?.view)
return

This happens for single statements only, that's why it works correctly in your 2nd case

More info: Implicit Returns from Single-Expression Closures

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.