Function Call

A function call has the form f(arg1, arg2, ..., argn). f indicates the name of the function to be called. arg1 to argn are the arguments used in the function call. The type of each argument must be a subtype of the corresponding parameter type. There can be zero or more arguments. When there are no arguments, a function call has the form f().

The way arguments are passed in function calling depends on whether parameters in the function definition are named or non-named parameters. The argument of a non-named parameter is an expression. The argument of a named parameter must be in the form p: e, where p is the parameter name and e is an expression (that is, value passed to p).

The following is an example of non-named parameters usage in a function call:

func add(a: Int64, b: Int64) {
    return a + b
}

main() {
    let x = 1
    let y = 2
    let r = add(x, y)
    println("The sum of x and y is ${r}")
}

The execution result is as follows:

The sum of x and y is 3

The following is an example of named parameters usage in a function call:

func add(a: Int64, b!: Int64) {
    return a + b
}

main() {
    let x = 1
    let y = 2
    let r = add(x, b: y)
    println("The sum of x and y is ${r}")
}

The execution result is as follows:

The sum of x and y is 3

If there are multiple named parameters, they can be passed in an order that differs from the order of these parameters in the function definition. In the following example, b can appear before a when the add function is called:

func add(a!: Int64, b!: Int64) {
    return a + b
}

main() {
    let x = 1
    let y = 2
    let r = add(b: y, a: x)
    println("The sum of x and y is ${r}")
}

The execution result is as follows:

The sum of x and y is 3

If a named parameter that has a default value is omitted in a function call, that default value is used as the argument. In the following example, if no argument is passed to the b parameter when the add function is called, the default value 2 is used as the argument of b:

func add(a: Int64, b!: Int64 = 2) {
    return a + b
}

main() {
    let x = 1
    let r = add(x)
    println("The sum of x and y is ${r}")
}

The execution result is as follows:

The sum of x and y is 3

Alternatively, if a named parameter that has a default value is supplied with a value in a function call, then that value is used as the argument and not the default value. In the following example, the value 20 is passed to the b parameter when the add function is called, and therefore the value of b is 20:

func add(a: Int64, b!: Int64 = 2) {
    return a + b
}

main() {
    let x = 1
    let r = add(x, b: 20)
    println("The sum of x and y is ${r}")
}

The execution result is as follows:

The sum of x and y is 21