More about Functions in Swift

Functions let you define reusable pieces of code that perform specific functionality.

Let’s start with a simple function

Now if you try to run this code nothing gets printed. Now you need to call this function greet().


So, now if you want to greet a user by their name then you need to send the name parameter inside the function and print it inside the function. So now let’s do that.

Internal and External Parameters Name

The parameter used inside the function is the Internal Parameter name and the parameter name which we pass while calling the function is called the External Parameter name.

For example, we could name the parameter username when it’s being called, and name inside the functions, like this:

You can also specify an underscore, _ as the external parameter name, which tells Swift that it shouldn’t have any external name at all. For example:

Return Values

Swift can return a value by writing -> then a data type after their parameter list. Now let’s write a function to return a value:

In this function, you can see a return data type of String. This function returns the Hello, username here username denotes the name we’re passing inside the function.

Default parameters

You can give your own parameters a default value just by writing an = after its type followed by the default you want to give it. So, we could write a greet() function that can optionally print canGreet:

greet() in this greet function, I have not passed the canGreet boolean value so by default, it's taking as true and returning Hello, username String in return.

in this greet function, I have passed the canGreet boolean value as false, So its returning only the username.

inout parameters

Parameters that are passed into a Swift function are constants, so you can’t change them. If you want, you can pass in one or more parameters as inout, which means they can be changed inside your function, and those changes reflect in the original value outside the function. For example

You first need to make a variable integer — you can’t use constant integers with inout, because they might be changed. You also need to pass the parameter to doubleInPlace using an ampersand, &, before its name, which is an explicit recognition that you’re aware it is being used as inout.

I’m an IOS, Flutter Developer. Working in a MNC, now a Blogger