In Swift parameter names are used when you call a method, except for the first parameter. Why is the first name not used?
Using a variation from the Swift manual;
var count2: Int = 0
func incrementBy2(amount: Int, numberOfTimes times: Int) {
count2 += amount * times}
This will work;
incrementBy2(2, numberOfTimes: 7)
However this gives me "Extraneous argument label 'amount' in call"
incrementBy2(amount: 2, numberOfTimes: 7)
Id there a reason for this or is it one of those "just the way it is" things?
This is to follow an convention we were all used to from Objective-C, where the name of the first parameter is combined with the method name. Here's an example:
- (void)incrementByAmount:(NSInteger)amount
numberOfTimes:(NSInteger)times
{
// stuff
}
You could call the method like:
[self incrementByAmount:2 numberOfTimes:7];
And it feels more natural to read by incorporating the name of the parameter into the method's name. In Swift, you can achieve the same with the following:
func incrementByAmount(amount: Int, numberOfTimes: Int) {
// same stuff in Swift
}
And call the method like:
incrementByAmount(2, numberOfTimes: 7)
If you don't want to use this convention, Swift gives you the ability to be more explicit and define separate internal and external parameter names, like so:
func incrementByAmount(incrementBy amount: Int, numberOfTimes: Int) {
// same stuff in Swift
// access `amount` at this scope.
}
You can call the method like this:
incrementByAmount(incrementBy: 2, numberOfTimes: 7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With