swiftsyntaxmutating-function

Mutating fun call swift syntax


I'm reading through the Swift 2.2 man and trying to understand a function in the mutating fun section here is the code

struct TestPoint {
    var x = 0.0, y = 0.0

    mutating func moveByX(deltaX: Double, y deltaY: Double) {
        self = TestPoint(x: x + deltaX, y: y + deltaY)
    }
}

var somePoint = TestPoint(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)

print("The point is now at (\(somePoint.x), \(somePoint.y))")

The part I'm having trouble is with the func moveByX syntax. y deltaY for example how is this allowed? y is the declared variable in the struct but where does the deltaY bit come in ?

Only two values are passed in somePoint.moveBy

Is the value passed to both y and deltaY ?

thanks for any help


Solution

  • Internal and external parameter names

    Let's look at the function signature of moveByX(...):

    mutating func moveByX(deltaX: Double, y deltaY: Double) 
        /*                  |            /  ^^^^^^- internal name      
                            |      external name
                internal name                                     */
    

    In Swift 2.2, by default the first function parameter as no external name (_), which means that the function moveByX(...) is called as:

    someTestPointInstance.moveByX(someXvalue, y: someYvalue)
        /*                        |           \
                    no external name         external name        */
                          
    

    This means that the y that you see in the signature of moveByX(...) is just an external parameter name, one that no longer has any use when we've entered the body of the function (where the internal parameter name, deltaY is used). So the second argument passed to moveByX(...), to the external parameter name y, will be referred (in this case, copied to) deltaY in the actual function body.

    Finally note that the x and y properties used in the body of the function

    self = TestPoint(x: x + deltaX, y: y + deltaY)
    

    are the member properties x and y as defined in the definition of the SomePoint struct.

    Is the above still valid for Swift 3.0?

    As somewhat covered above: if we don't supply explicit external parameter names for function parameters in Swift 2.2, then the following rules apply:

    In Swift 3.0 all parameter names follows the second rule above, namely; if no external parameter name has been supplied, then the internal parameter name will be used as external parameter name for all parameters.

    That means the example above would have to be modified into something along the lines

    struct TestPoint {
        var x = 0.0, y = 0.0
    
        mutating func moveBy(x deltaX: Double, y deltaY: Double) {
            self = TestPoint(x: x + deltaX, y: y + deltaY)
        }
    }
    
    // called as 
    someTestPointInstance.moveBy(x: someXvalue, y: someYvalue)