UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)")
}
myName2("Anna")

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

2      

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.

3      

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.

3      

Thank you very much!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.