in , ,

Swift Functions

Swift Functions
Swift Functions

Swift Function: In Swift you use functions to perform specific tasks in your code. It’s that straightforward! Functions can take input and produce output. They are especially useful for creating a reusable assignments and activities in your code.


What is a function?

A function is a group of statements that defines an activity to be performed. The main use of a function is to make the code reusable.

Non technically, you can consider a function a machine. A machine plays out a particular task, asks for input, processes the input and returns the output.


Types of Functions

Contingent upon whether a function is predefined or created by programmer; there are two types of function:

  1. Library function- Functions that are defined already in Swift Framework.
  2. User-defined functions – Functions created by the programmer themselves.

Library Functions

Library functions are built-in functions that are already defined in Swift framework. These functions are available to take care of common issues in Swift with the goal that you don’t need to tackle them yourselves. They are straightforward activities like printing, finding minimum and maximum, and so on

You can use library work straightforwardly by invoking (calling) it. On the off chance that you need, you can see every one of the functions inside the Swift framework. Simply write import Swift, press Cmd and Click it. You will explore to a new page. Search every one of the statements beginning with func watchword.

Example 1: Library or Built in Function

print("Hello, World!")

At the point when you run the above program, the output will be:

Hello, World!

In the above program, we have invoked a built-in print function defined in Swift Framework. The function is used to print output in the console.

We can call print() work since Swift framework is consequently imported into our Playground. Else, we ought to have imported it ourselves by writing import Swift.


User defined Functions

Quick likewise allows you to define your own function. Creating your own function assists with writing code to tackle issues or perform tasks not accessible in Swift Framework. You can likewise reuse your function to perform comparable tasks later on.


Defining a Function

func function_name(args...) -> ReturnType {
    //statements
    return value
}

Lets describe every segments in brief:

  • func is the catchphrase you should write to create a function
  • function_name is the name of a function. You can give it any name that defines what a function does.
  • args… defines the input a function acknowledges.
  • > This operator is used to show the return sort of a function.
  • ReturnType defines the type of a worth you can get back from a function. For example Int, String and so on
  • return catchphrase is used to move the control of a program to the function call and furthermore return vlue from a function.

Even if you don’t determine the return watchword the function returns automatically after execution of last statement.

value addresses the actual data being returned from the function. The worth sort should coordinate with the ReturnType.


How function works?

In the above diagram, the statement function_name(args) invokes/calls the function with argument values args, which at that point leaves the current part of code (for example quits executing statements underneath it) and starts to execute the first line inside the function.

  1. The program comes to a line of code func function_name(Args…) and acknowledges the values args passed during the function call function_name(args).
  2. The program at that point executes the statements statementsInsideFunction defined inside the function.
  3. The statements inside the function are executed in top to bottom order, one after the other.
  4. After the execution of the last statement, the program leaves the function and returns to where it began from i.e function_name(args).
  5. let val = stores the worth returned from the function in a constant val. Also, you can store in a variable as var val =.
  6. From that point forward, statements statementsOutsideFunction are executed.

Example 2: How to define a function in Swift?

func greet(user:String) {
    print("Good Morning! \(user)")
}

Above shown is a function definition which comprises of following parts:

  1. Watchword func marks the beginning of function header.
  2. greet is a function name to uniquely identify and call work in the program.
  3. (user:String) marks the finish of capacity header and acknowledges a parameter of type String.
  4. The function comprises of a print statement inside the body which executes after you call the function.

Calling a function

Whenever you have created a function, you can call it in your program to execute the statements proclaimed inside the function. To call a function you just write the function name followed by ()and pass the input parameters inside it as:

greet(user: "Isac")

Example 3: Calling a function in Swift

func greet(user:String) {
    print("Good Morning! \(user)")
}

greet(user: "Isac")

At the point when you run the above program, the output will be:

Good Morning! Isac

In the above code, greet(user: “Isac”) calls the function and passes value Isac of type String. From that point forward, print statement inside the function executes.


Return Statement

The return watchword advises the program to leave the function and return to line where the function call was made.

You can likewise pass value with the return watchword where worth is a variable or other data returning from the function.

Example 3: Function with return keyword

func greet(user:String)-> String {
    return "Good Morning! \(user)"
}

let greeting = greet(user: "Isac")
print("""
     You have a new message
     \(greeting)
     """)

At the point when you run the above program, the output will be:

You have a new message
Good Morning! Isac

In the above code, greet(user: “Isac”) calls the function and passes value Isac of type String. return “Good morning! (user)” statements returns the worth of type String and moves the program to the function call.

let greeting= stores the worth returned from the function. After the function returns, the print statement beneath the function call executes.


Things to remember

  • Give a function name that reflects the reason for the function.
  • A function ought to achieve just one assignment. In the event that a function accomplishes more than one task, break down it into various functions.
  • Attempt to think early and group statements inside a function which makes the code reusable and modular.

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Swift Dictionary

Swift Dictionary

Swift Function Parameters and Return Values

Swift Function Parameters and Return Values