Functions in Swift

Functions.png

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

Let's start with simple function

                func greet(){
    print("Hello, Everyone")
}
            

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

                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.

                func greet(name: String){
    print("Hello, \(name)")
}

greet(name: "Joel D'souza")
            

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:

                func greet(username name: String){
    print("Hello, \(name)")
}

greet(username: "Joel D'souza")
            

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:

                func greet(_ name: String) -> String {
    return "Hello, \(name)"
}

print(greet("Joel D'souza"))
            

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 and get more readers

Join other developers and claim your FAUN account now!

Stats
21

Influence

877

Total Hits

1

Posts

Discussed tools