Swift programming for Beginners – Swift Functions

(Swift for Beginners)

Swift Functions

In this article, you’ll learn everything about functions, what is a function, syntax, types in Swift with examples.

What is a function?

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

Non technically, you can think of a function as a machine. A machine performs a specific task, asks for input, processes the input and returns the output.


Types of Functions

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

  1. Library functions – 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 present to solve common problems in Swift so that you don’t have to solve them yourselves. They are simple operations like printing, finding minimum and maximum, etc.

You can use library function directly by invoking (calling) it. If you want, you can see all the functions inside the Swift framework. Just write import Swift, press Cmd and Click it. You will navigate to a new page. Search all the statements starting with func keyword.

Example 1: Library or Built in Function

print("Hello, World!")

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 are able to call print() function because Swift framework is automatically imported into our Playground. Otherwise, we should have imported it ourselves by writing import Swift.


User defined Functions

Swift also allows you to define your own function. Creating your own function helps to write code to solve problems or perform tasks not available in Swift Framework. You can also reuse your function to perform similar tasks in the future.


Likewise, Functions can also be categorized in the basis of parameters and return statements. See the article Swift Function Parameter Types and Return Types.


Defining a Function

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

Lets describe each components in brief:

  • func is the keyword you must 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 accepts.
  • -> This operator is used to indicate the return type of a function.
  • ReturnType defines the type of a value you can return from a function. E.g. IntString etc.
  • return keyword is used to transfer the control of a program to the function call and also return value from a function.
    Even if you don’t specify the return keyword the function returns automatically after execution of last statement.
  • value represents the actual data being returned from the function. The value type must match the ReturnType.

 


How function works?

How function works in Swift?

In the above diagram, the statement function_name(args) invokes/calls the function with argument values args, which then leaves the current section of code (i.e. stops executing statements below it) and begins to execute the first line inside the function.

  1. The program comes to a line of code func function_name(Args...) and accepts the values args passed during the function call function_name(args).
  2. The program then 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 goes back to where it started from i.e function_name(args).
  5. let val = stores the value returned from the function in a constant val. Similarly, you can store in a variable as var val =.
  6. After that, 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 consists of following components:

  1. Keyword func marks the start of function header.
  2. greetis a function name to uniquely identify and call function in the program.
  3. (user:String) marks the end of function header and accepts a parameter of type String. See the article Swift Function Parameter Types and Return Types that defines function with parameters.
  4. The function consists of a print statement inside the body which executes after you call the function.

 


Calling a function

Once you have created a function, you can call it in your program to execute the statements declared inside the function. To call a function you simply 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")

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 valueIsac of type String. After that, print statement inside the function executes.


Return Statement

The return keyword tells the program to leave the function and return to line where the function call was made.

You can also pass value with the return keyword where value is a variable or other information coming back 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)
     """)

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 Stringreturn "Good Morning! (user)" statement returns the value of type String and transfers the program to the function call.

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


Things to remember

  • Give a function name that reflects the purpose of the function.
  • A function should accomplish only one task. If a function does more than one task, break down it into multiple functions.
  • Try to think early and group statements inside a function which makes the code reusable and modular.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!