Functions in Swift

#Programming   #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:

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")
Screenshot 2021-08-23 at 2.42.34 PM.png

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:

Screenshot 2021-08-23 at 2.58.36 PM.png

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:

Screenshot 2021-08-23 at 3.01.29 PM.png

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.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

15

Authority

168

Total Hits

Discussed tools
Swift