Using Function Parameter Names in Swift

后端 未结 5 538
逝去的感伤
逝去的感伤 2020-12-10 13:10

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;

5条回答
  •  星月不相逢
    2020-12-10 14:03

    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)
    

提交回复
热议问题