Join us

Functions in Swift

Functions.png

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

Let's start with simple function

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

output:

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:

Output:

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 for 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.


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity
26

Influence

3k

Total Hits

1

Posts