Question about Function

HI there!

I have a few questions:

  1. What the word ‘for’ mean in function declaration, for example:

func some(for parameter: String) -> String{
parameter + “a”
}

  1. What is underline mean in function declaration, for example:

func some(_ parameter: String) -> String{
parameter + “a”
}

Thanks!

Hi @yevh Welcome!

You first example, I am not sure unless the ‘for’ is the external name for the parameter. Smarter minds than mine will know. Stand by,

In your second example, the underscore ( _ ) is a placeholder for the external name of of the parameter.

func myFunc( extName paramName:String) {
}

func myFunc( _ paramName:String) {
}

Both above accomplish the same thing.

Blessings,
—Mark

HI @FoundationSW !

But for what we need external name of the parameter at all? Maybe there some specific cases where it can be used?

Thank you a lot!

If you have a lot of code, external names helps you keep track what the parameters are used for.

My code is so simple, I regularly use place holders. :slight_smile:

Blessings,
—Mark

Strictly speaking, you don’t need them when writing your own functions. But it’s a bit of sugar that make Swift code easier to read and understand. It helps to make your code more readable and, therefore, more maintainable.

To quote the official Swift docs: “The use of argument labels can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent.”

And the example used in the docs:

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill! Glad you could visit from Cupertino."

Here both the function body and the call site read smoothly and the intent is well established.

Without argument labels, your call site would be something like this:

print(greet(person: "Bill", hometown: "Cupertino"))

which doesn’t read as nicely. But if you just used the argument label without a separate parameter name, then your function would be something like this:

func greet(person: String, from: String) -> String {
    return "Hello \(person)! Glad you could visit from \(from)."
}

and that doesn’t read well either.

1 Like

@roosterboy many thanks!