BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Parameter Labels

Forums > SwiftUI

Hi.

I have learned SwiftUI.

func sayHello(to name: String) { print("Hello, (name)!") } The parameter is called to name, which means externally it’s called to, but internally it’s called name. This gives variables a sensible name inside the function, but means calling the function reads naturally:

sayHello(to: "Taylor")

I didnt understand this sentence.( but means calling the function reads naturally) I understand how can use parameter labels.But ı am trying to understand why we use this. Paul said variables has sensible names thanks to the this . But also we used it before as name . Why we use 'to' word and what does it means this sentence?( but means calling the function reads naturally)

Please help me. Thanks.

3      

It helps make Swift code read more like English sentences.

If we just use the parameter name (in this case name), then we get something like this:

func sayHello(name: String) {
    print("Hello \(name)!")
}

and, at the call site:

sayHello(name: "Paul")

which, when read as an English sentence, would be Say hello name "Paul".

But if we use argument labels, we would get:

func sayHello(to name: String) {
    print("Hello \(name)!")
}

sayHello(to: "Paul")

//in English: Say hello to Paul

And isn't that much nicer to read?

And we still get to use name inside the function. If we just used to as the parameter name, we'd end up with this:

func sayHello(to: String) {
    print("Hello \(to)!")
}

which doesn't make a lot of sense in the context of the function. Parameters should have names that tell you something about what they are and what they are used for. to doesn't really tell you much of anything.

So using argument labels lets us have the best of both worlds.

4      

Well said @roosterboy

Would like to add that you can also use _ underscore for the external parameter name then in call site you do have to use anything, however you have to have the internal parameter name still.

func hello(_ name: String) {
    print("Hello \(name)")
}

hello("Paul")

4      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.