Swift program to create a function with default arguments

Here, we are going to learn how to create a function with default arguments in Swift programming language?
Submitted by Nidhi, on June 24, 2021

Problem Solution:

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

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.

Swift User-defined Functions Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.