(no title)
Watabou | 8 years ago
For example, you can have a function like so:
func greet(with greeting: String, to personName: String) {
print("\(greeting), \(personName)!")
}
In the above code, "with" and "to" are external names, and are only available when calling the function but are not available inside the function itself. So you would call this function like so: greet(with: "Hello", to: "Bob")
Now if you want to exclude the external name to call the functions, you use the "_" syntax. So you're right that it denotes an unused parameter. In this case, it's an unused external parameter name.
saghm|8 years ago
ridiculous_fish|8 years ago
The internal/external name divide often works out beautifully. For example, let's equip Double with a multiply-add. An idiomatic Swift signature:
Erase punctuation and you have: The caller sees an action (multiply by, adding), the callee sees nouns (multiplier, summand). It's fantastically readable.jurip|8 years ago
masklinn|8 years ago
Most definitely yes. In fact it used to be that the first parameter was implicitly positional (in Swift 2 IIRC), this was removed to make all parameters named by default.
And do note that you can provide a single label for a parameter, it will be used as both "internal" and "external" names:
> and is using different external names so commonAlso yes, it's absolutely ubiquitous, if only because that's the one way to provide "positional" parameter.
derefr|8 years ago
thramp|8 years ago
masklinn|8 years ago
manmal|8 years ago
Watabou|8 years ago
For the first versions of Swift, they actually had two versions. For functions (i.e not functions inside classes), you didn't have to have named arguments for the first parameter, but you did for methods (functions inside classes).
They explicitly added it for Swift 3 to make it more consistent with method.
I think I like the consistency more, but I do agree "_" is ugly. I don't have an idea of what else they could do though. I don't want Swift to make the parameter names optional, since no one would use it (like in Python, I rarely see named arguments being used)
Grustaf|8 years ago
I think argument labels are great, makes the code much more readable.