Open In App

How to Swap Array items in Swift?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Swift supports various generic collections like set, dictionary, and array. In Swift, an array is an ordered collection that is used to store the same type of values like string, int, float, etc. In an array, you are not allowed to store the value of a different type in an array, for example, if you have an int type array in this array you are not allowed to store float values, if you try to do so you will get an error. It also keeps duplicate values of the same type. An array can be mutable and immutable. In the Swift array, we can swap the position of the elements. To do so we use the swapAt() function. This function swap two values of the array at the given position.

Syntax:

arrayName.swapAt(val1, val2)

Here, 

arrayName is the object of the array class.

Parameter: This function takes two parameters, i.e., val1 and val2. Here val1 represents the position of the first element to swap and val2 represents the position of the second element to swap.

Return Value: It does not return any value. Instead, it swaps the specified elements.

Example 1:

Swift




// Swift program to swap the element of the array
import Swift
  
// Creating an array of number
// Here the array is of float type
var newNumber = [23.034, 1.90, 9.1, 32.34, 560.44, 21.23]
  
print("Array before swapping:", newNumber)
  
// Swapping the element of the array 
// Using swapAt() function
newNumber.swapAt(1, 2)
  
// Displaying the final result
print("Array after swapping:", newNumber)


Output:

Array before swapping: [23.034, 1.9, 9.1, 32.34, 560.44, 21.23]
Array after swapping: [23.034, 9.1, 1.9, 32.34, 560.44, 21.23]

Example 2:

Swift




// Swift program to swapping the elements of array
import Swift
  
// Creating an array of Emp Name
// Here the array is of string type
var GfgEmpName = ["Sumit", "Poonam", "Punit", "Bittu", "Mohit"]
  
print("Geeks's employee name before swapping:", GfgEmpName)
  
// Swapping the two elements of the GfgEmpName array
// Using swapAt() function
GfgEmpName.swapAt(2, 4)
  
// Displaying the final result
print("Geeks's employee name after swapping: ", GfgEmpName)


Output:

Geeks's employee name before swapping: ["Sumit", "Poonam", "Punit", "Bittu", "Mohit"]
Geeks's employee name after swapping:  ["Sumit", "Poonam", "Mohit", "Bittu", "Punit"]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads