Connect with us

Hi, what are you looking for?

Programming

Functions In Swift Programming

Functions In Swift Programming
Functions In Swift Programming

Functions are pieces of code that combine the integrity of the code used to perform a task into a single structure.

If you are familiar with C programming or Objective-C, you can quickly grasp the structure of functions available in Swift.

Defining Function and Calling

A simple function in Swift looks like the following, it doesn’t return any value, it just executes a block of code.

func funcName()
{
  // Code is here!
}

While calling the function, the values to be used in the function can be entered, we identify these values as parameters.

func funcName(paramaterName: DataType)
{
  // Code is here!
}

When defining a function in Swift, if it is to return a value, the type of data it will return is specified. Types other than the type to be returned cannot be used with the return statement.

// 2 Integer Parameter & Return Int
func addition(num1: Int, num2: Int) -> Int
{
  // Sum of 2 parameter
  let sum = num1 + num2 
  // Function Value = sum
  return sum
}

This is how you can define the sum function that gives the sum of two numbers. When the return command is executed, the value of your function will be returned value.

If the data type to return is not given, the function becomes void type (non-returning function) and the return statement cannot be used.

// Void Function
func addition(num1: Int, num2: Int)
{
  let sum = num1 + num2 

  // Can't Return
  print(sum)
}

Unless your functions are called, they will not run actively on the program, it is easy to call functions just write the name and specify parameters.

To call a function, we only need to know its name and required parameters. Attention, you must also write the parameter name, only the value is not accepted.

print("12 + 4:" , addition(num1:12 , num2:4))
print("13 + 7:" , addition(num1:13 , num2:7))
print("15 + 9:" , addition(num1:15 , num2:9))

// 12 + 4: 16
// 13 + 7: 20
// 15 + 9: 24

Now the function started to work, the function matching its name was run, the parameters were collected and the function returned this sum value.

Return Statement in Function

The return statement is an element that makes a function important, “return” is used to store values in the function (without using any variables).

Although its definition is simple, it is an important and frequently used item in coding, now let’s move on to examples.

func founder(text:String , element:Character) -> String
{
  // Speperate Char in Text
  for i in text
  {
    // Compare characters
    if i == element
    {
      // Return if found element
      return "Detected: " + String(element)
    }
  }

  
  // Return if not found
  return "Not Found"
}

// Print
print(founder(text:"xyzdsdsgh" , element:"g"))

// Detected: g

A simple linear search algorithm code is given above. The function checks whether the desired character exists in the text received from the user.

The function here returns a string, therefore the char expression should be converted to a string, now let’s re-encode it without the return statement.

func founder(text:String , element:Character)
{
  // Speperate Char in Text
  for i in text
  {
    // Compare characters
    if i == element
    {
      print("Detected")
    }
  }
}

// Print
print(founder(text:"xyzdsdsgh" , element:"g"))

// Detected
// ()

Did you notice something that even though the function is empty, an empty tuple is returned, yes, the void function also returns a value, we say that it does not return data because it is just an empty tuple.

Now we know how the functions work, but we have a problem, if the user does not enter a parameter, we get an error, we don’t want this, let’s solve it now.

Default Parameters in Function

Even if you or the user do not enter a value, you can protect the parameter from these factors by giving it a default value.

As an example, let’s write a greeting function and use a parameter value called guest if no name is entered.

// Default Parameter is Guest
func Hi(name: String = "Guest") -> String
{
  // Return value
  return "Hi " + name
}

print(Hi(name:"Alex"))
print(Hi())

// Hi Alex
// Hi Guest

If your application error is due to an empty parameter, it will annoy users. Therefore default parameter is important.

Using Function Types

You can store your functions in a variable the same way you store String or Int data types. Generally, this property is used to changing the name of the function.

func Hi(name: String) -> String
{
    return "Hi " + name
}

var Communicate: (String) -> String = Hi
print(Communicate("Mark"))

Here we assign the function Hi to a variable of type function. Now let’s explain the piece of code here a little more.

Every function you create is a “function data type” (composite data type), so you can assign that data type to different variables.

Traditional data types take a single value, but composite data types (arrays, tuples, functions) can take and store multiple values.

print("Data Type:",Comunicate)

// (Function)

As you can see, Swift specifies the data type as “function”, function data types are composite data types so it can store multiple codes (like an array).

func addition(num1: Int , num2: Int) -> Int 
{
    return num1 + num2
}

// Assignment "Addition" Func to "Add"
var add = addition
print(add(1,2))

When assigning a function to a variable of another function type, simply typing the name of the function will suffice.

Using Function Types as Parameter Types

The title may have sounded a bit complicated, don’t worry, we are in a simple section. You can use the value returned by a function as a parameter.

If you use the function type as the parameter type, you can process the value you created in a function and return it again.

// Addition Function
func addition(num1: Int , num2: Int) -> Int
{
  return num1 + num2
}

// subtraction function
func subtraction(num1: Int , num2: Int) -> Int
{
  return num1 - num2
}

// show these function result
func showOperation(_ mathFunc: (Int , Int) -> Int, value: Int , value2: Int)
{
  print(mathFunc(value , value2))
}

showOperation(subtraction , value:12 , value2:2)

// 10

In the function here, we have prepared a parameter for a function with 2 Int parameters that will return an Int value as a parameter, and we have also created 2 separate parameters to fill the parameters in the function.

This method can be useful the next time you use a function for a different job in a different function.

Now let’s explain step by step how to do this for those who want to use a function as a parameter.

  • Prepare functions to be used in another function.
  • Create your main function and set previous created function as parameter (What data type the function returns and the data type of its parameters are important.)
  • If the function you use as a parameter has parameters, add the parameters to your main function as well.
  • Write the function body.

I’ve listed the steps for you to understand. Although this method is not used much, it may be useful for you.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Programming

This article is prepared to explain concepts that will be important for programming beginners such as data types, variables, heap and stack, and operators....

Programming

This article was created for those who want to use functional programming in their career or who are learning new programming paradigms. We will...

Programming

Computers can solve an event in different ways, we call these ways algorithms, each algorithm works differently from the others and has different processing...

Data Science

SQL (Structured Query Language) is one of the most used tools by data scientists, data analysts, and data engineers. Almost all companies use a...