Optional Parameter With Default Value In Swift Function


In app development, we often have to create Swift functions with optional parameters that have default values. For example, if we don’t pass the parameter during the function call, it will take some default values.

If a function parameter has a default value set during the creation of the function, then it will not return any error whether we pass the parameter or not during the function call.

Creating a Swift function with default parameter value

Now let’s take a look at the example below where we have created a Swift function by providing a default value to the parameter:

func myFunc(fruitName: String = "Apple") {
    print("Fruit is \(fruitName)")
}

// Call the function without providing any argument
myFunc()

// Call the function with parameter or argument
myFunc(fruitName: "Banana")

Output:

Fruit is Apple
Fruit is Banana

In the above code, we also call the function both without a parameter and with a parameter.

You can notice that, if we call the function without any parameter, it is functioning with the value we set during the creation of the function. This is the default value of the parameter.

In the second time, we are providing the parameter with an assigned value when we call the function. In that case, we can see that it replaces our default parameter value with the provided value.

Let’s see another example

Below is given another example of the Swift program for optional parameter:

func flowerAndFruit(flowerName: String,fruitName: String = "Apple") {
    print("Fruit is \(fruitName) and flower is \(flowerName)")
}



flowerAndFruit(flowerName: "Rose")

flowerAndFruit(flowerName: "Iris", fruitName: "Banana")

Output:

Fruit is Apple and flower is Rose
Fruit is Banana and flower is Iris

This time, the first argument flowerName is a required parameter as we have not set the default value during the creation of the function.

But we provide a default value for the second parameter fruitName. For this reason, the second parameter becomes an optional parameter and it is not required to specify the second parameter when we call the function. We only have to provide it if we want to change the parameter value other than the default.

In this way, the first parameter is required and the second one is optional.