0
0
Swiftprogramming~5 mins

Default parameter values in Swift

Choose your learning style9 modes available
Introduction

Default parameter values let you give a starting value to a function's input. This way, if you don't provide that input, the function still works smoothly.

When you want a function to work even if some inputs are missing.
When you want to avoid writing many versions of the same function.
When you want to provide common or typical values automatically.
When you want to make your code easier to use and read.
Syntax
Swift
func functionName(parameterName: Type = defaultValue) {
    // function body
}

You write the default value after an equals sign = in the parameter list.

If you call the function without that parameter, the default value is used.

Examples
This function says hello. If you don't give a name, it uses "Friend".
Swift
func greet(name: String = "Friend") {
    print("Hello, \(name)!")
}
This function multiplies a number by a multiplier. If you don't give the multiplier, it doubles the number.
Swift
func multiply(number: Int, by multiplier: Int = 2) -> Int {
    return number * multiplier
}
Sample Program

This program shows how the greet function works with and without giving a name.

Swift
func greet(name: String = "Friend") {
    print("Hello, \(name)!")
}

greet()
greet(name: "Alice")
OutputSuccess
Important Notes

Default parameters must come after parameters without defaults.

You can mix parameters with and without default values in the same function.

Summary

Default parameter values make functions easier to call by providing fallback inputs.

They help avoid writing many similar functions.

Use them to make your code cleaner and friendlier.