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

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.