Question regarding calling a function with a closure parameter

Hello, total Swift beginner here and I apologize in advance if this is a silly question.

Screen Shot 2021-06-19 at 11.47.58 PM

I'm just wondering why the argument true for the completion closure needs to be passed in inside the body of the function? Why can it not be passed in when the actual function upload is called? Why do you have to give it an arbitrary parameter name (success in this case)?

Thanks for your help.

The func declaration, translated out of Swift and into plain English, means, “If you give me a file URL and a way to report back whether or not I succeeded, then I can perform an upload for you.”

The call site means, “Here is a file URL, and here is how to tell me whether or not it worked when you are done, now please perform the upload.”

Logically, it is the function that decides what did or didn’t work. Whatever is asking the function to make the attempt cannot know in advance whether it will succeed.

You just need a way to refer back to it when you use it in the following lines. If you do not care about having an expressive name, you can use the default $0:

upload(fileURL, completion: {
  print("File upload success is: \($0)!")
})
3 Likes

Thank you very much Jeremy!

One reason the example is confusing is that you don’t see the completion being called on the failure path. But presumably somewhere in the elided code (where the comment says “Uploads the file”) is something along the lines of:

do {
   try sendFileToServer(data: dataFromFileURL)
} catch {
   completion(false)
}

So the function is meant to take a completion that is called whether the upload succeeds or not, and the success parameter on the completion closure indicates which of those is the case.

1 Like

Thanks Christopher!

Terms of Service

Privacy Policy

Cookie Policy