WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 6: Closures Why I don't need to call the closure with a parameter name?

Forums > 100 Days of Swift

I am on day 6 and I have a question about this code:

func myName(someName: String) {
    print("My name is \(someName)")
myName(someName: "Anna") 

let myName2 = {(someName: String) in
    print("My name is \(someName)")

Why I don't need to use the parameter name for the closure, but I need to use it when calling the function? I will get an error if I skip the parameter name for the function or if I use it for the closure. I am sorry if this is a stupid question from a total beginner


As far as I know, closures don't have external parameter names so they have only internal parameter names. That is why you don't need to use them. A function can have both external and internal parameter names e.g.

func someFunction (externalName internalName: Int) {
// here you use internalName for argument

to call a function

someFunction(externalName: 2)

as closures do not have exernal name so you have to omit them.

Hope this is clear.


Jus to add :)

External parameter names are so standard in Swift that there’s a rule: by default, all parameter names are externalized automatically, using the internal name as the external name. If you want a parameter name to be externalized, and if you want the external name to be the same as the internal name, do nothing — that will happen all by itself. If you want to depart from the default behavior, you can do either of the following in your function declaration:

Change the name of an external parameter If you want the external name of a parameter to be different from its internal name, precede the internal name with the external name and a space.

Suppress the externalization of a parameter To suppress a parameter’s external name, precede the internal name with an underscore and a space.

But this is not the case for closures :) they are internal.


Thank you very much!


Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.