Swift program to return an array from the function

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write a swift program to return an array from the function.

In Swift, a function is a set of statements that is used to solve some specific problem. It is defined using func keyword. We can call the function with the help of its name.

Function Declaration − It is used to tell compiler about  function’s name, parameters and return types.

Function Definition − It represent the body of the function.

Syntax

  • Following is the syntax of a function

func functionName(para1 : Type, para2 : Type)-> returnType{ 
   // Body 
}

An array is an order ed collection which is used to store same type of data. It can be mutable or immutable.

  • Following is the syntax of an array −

var myArray = [Type]() 
Or 
var myArray = [value1, value2, value3]

Swift allows you to return an array from the function. To do so we just simple declare a function with array as a return type.

  • Following is the syntax −

func functionName(para : [Type])-> [ReturnType]{
   // Body 
}

Example 1

The following program shows how to return an array from the function.

import Foundation import Glibc // Function which takes and return an array func sortArray(arr: [Int]) -> [Int]{ var mArr = arr print("Original array:", mArr) // Sorting an array mArr.sort() // Returning an array return mArr } // Passing array to the function and // display the sorted array print("Sorted array:", sortArray(arr: [87, 54, 2, 5, 48, 3, 56, 1]))

Output

Original array: [87, 54, 2, 5, 48, 3, 56, 1] 
Sorted array: [1, 2, 3, 5, 48, 54, 56, 87]

Here, in the above code, we create a function named sortArray(). This function takes array as an argument and return a sorted array. In the sortArray(), we passed the array at the time of function calling: sortArray(arr: [ 87, 54, 2, 5, 48, 3, 56, 1]) and return sorted array that is [ 1, 2, 3, 5, 48 54, 56, 87]

Example 2

The following program shows how to return an array from the function.

import Foundation import Glibc // Function which takes and return an array func myArray(arr: [String]) -> [String]{ var mArr = arr print("Original array:", mArr) // Swapping the elements of an array // at 2 and 3 position mArr.swapAt(2, 3) // Returning an array return mArr } // Passing array to the function and // display the shuffled array print("Swapped array:", myArray(arr: ["Momo", "Pinky", "Amu", "Chinky", "Lio"]))

Output

Original array: ["Momo", "Pinky", "Amu", "Chinky", "Lio"] 
Swapped array: ["Momo", "Pinky", "Chinky", "Amu", "Lio"]

Here, in the above code, we create a function named myArray(). This function takes an array as an argument and returned a swapped array. In the myArray(), we passed the array at the time of function calling: myArray(arr: ["Momo", "Pinky", "Amu", "Chinky", "Lio"] and return an swapped array: ["Momo", "Pinky", "Chinky", "Amu", "Lio"]

raja
Updated on 10-Oct-2022 12:31:23

Advertisements