Demystifying Views in iOS · Parent Views | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4518-demystifying-views-in-ios/lessons/11

I have a quibble about the implementation of the completion closure of UIView.animate method in the animateIn method shown at the end of the video. It’s admittedly quite clever to use a map function to determine whether the handleCompletion closure passed in as a parameter is nil or not, but it’s probably also not at all obvious what’s going on or how it works at first glance. (At least it wasn’t for me.)

If the intention is something like, “For the the completion closure of UIView.animate method, call the handleCompletion closure if it’s non-nil.”, couldn’t this be written much more simply like the code below?

completion: { _ in handleCompletion?() }

@catie @jessycatterwaul @jcatterwaul Can you please help with this when you get a chance? Thank you - much appreciated! :]

completion: { _ in handleCompletion?() } dictates: “When the animation completes, disregard whether or not the animation actually finished, and call handleCompletion if it is has a value.”

What we did in the video is equivalent to this (I think of Optional.map as a common abbreviation for this sort of guard statement):

completion: {
  guard let handleCompletion = handleCompletion
  else { return nil }

  return { _ in handleCompletion() }
} ()

That dictates: “When the animation completes, don’t do anything. …unless handleCompletion had a value! If it did, disregard whether or not the animation actually finished, and call handleCompletion.”

On one hand, I appreciate the simplicity of your solution in terms of lines of code. But on the other, we know that handleCompletion can be checked for a value before the animation is complete, so waiting until that point isn’t necessary, and Swift unfortunately doesn’t make it as concise to describe that. Because it is cumbersome to be that explicit, I wouldn’t fault you for going with the option you proposed. I appreciate you asking about this; Catie and I had to ask ourselves how we ought to go about it as well!

Thanks for your reply. I appreciate the clarification, and it’s nice to know that we were thinking along the same lines about how this code should work.

1 Like