Q:

Swift program to create a function with default arguments

belongs to collection: Swift User-defined Functions Programs

0

In this program, we will create a user-defined function with default arguments. Using default arguments, we can use default values of arguments.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create a function with default arguments is given below. The given program is compiled and executed successfully.

// Swift program to create a function 
// with default arguments

import Swift

func AddNums(num1:Int=7,num2:Int=5,num3:Int=3){
    var sum = 0
    
    sum = num1 + num2 + num3
    
    print("Addition is: ",sum)
}

AddNums(num1:10)
AddNums(num1:10,num2:20)
AddNums(num1:10, num2:20,num3:30)

Output:

Addition is:  18
Addition is:  33
Addition is:  60

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift;

Here, we created a user-defined function AddNums(). The AddNums() function contains three arguments with some default values and calculated the sum of arguments. After that, we called functions with a different number of arguments and printed the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Swift program to implement a verdict function... >>
<< Swift program to return an array from a user-defin...