Blog / June 4, 2022 / 3 mins read / By Mahi Garg

Named and Unnamed Parameters: Swift

Functions are something that every developer uses daily. A function can of with or without parameters. Swift has multiple ways of passing the parameters to a function. we can alias the parameter name or we can even skip the parameter name while calling the function.

The parameter inside the function will still be used by its own name only but while calling the function, the name of the parameter can be replaced or even removed based on the function signature.

Let’s look at them one by one.

Below is a normal function with a single parameter and calling it using the parameter name

    func doSomething(number : Int){
        //I'll do some rocket science here,
        //and at the end, will just print the param
            print (number)
    }
    doSomething(number: 100)

In order to call the above function, we need to write the parameter name. In the above case the parameter name was number .


Sometimes it’s tedious to write the parameter name again and again or sometimes the function name itself is enough to make understand what that function is responsible for.

In those cases, in order to skip the parameter name every time we call that function, it can be preceded with an underscore _ which will make the parameter name unnamed.

func doSomethingWithNumber(_ number : Int){
    //I'll do some rocket science here,
    //and at the end, will just print the param
    print (number)
}
doSomethingWithNumber(100)

Here in the above example, we added an underscore _ in front of the parameter name which made the parameter unnamed. In order to call this function now, we don’t have to add the parameter name ie number in our case.

Keep in mind that we can’t even use the parameter name now. Underscore _ doesn’t make it optional but it actually made it unnamed.


We can even provide an alias to the parameter after which the parameter will be used with the new alias name instead of the original parameter name.

func doSomething(with number : Int){
    //I'll do some rocket science here,
    //and at the end, will just print the param
    print (number)
}
doSomething(with: 100)

In the above example, we added with as an alias name for the parameter. Now in order to call this function, we need to use with as the parameter name instead of number.

Keep in mind that this is not optional to use as a parameter name but it is mandatory.


Also, in all the cases, the parameter inside that function will still be used as its own name only. There is no change in that.

Comments