In this tutorial you will learn about the Swift Default Arguments and its application with practical example.
Swift Function Argument
In Swift, we pass information in function call as its arguments and the function can either returns some value to the point it where it called from or returns nothing.
Swift Default Arguments
In Swift, we can assign default parameter values in a function definition, so when we call that function with no argument passed for a parameter then its default value assigned. When a function is called with argument, then these arguments is used as parameter values in function, but when a function is called or invoked without passing argument for any specific parameters than default parameter values been used as parameters value as per function definition.
Syntax:-
1 2 3 |
func <fun_name>(<param1_name: param1_type,param2_name: param2_type = default_value>) -> returnType { // function body } |
Example :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* n1 : default argument is 5 n2 : default argument is 10 */ func addnum(n1:Int = 5, n2:Int = 10){ let result:Int = n1+n2 print("Sum of \(n1) and \(n2) is : \(result)") } print("W3Adda - Swift function with default arguments") // Call with all arguments addnum(n1:15,n2:25) // Call with some arguments addnum(n1:15) // Call with no arguments addnum() |
Output:-