Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Array swapAt()
In this tutorial, we will learn about the Swift array swapAt() method with the help of examples.
The swapAt() method swaps two elements at the specified indices of the array.
Example
var numbers = [2, 6, 4, 8]
// swap 6 and 4
numbers.swapAt(1, 2)
print(numbers)
// Output: [ 2, 4, 6, 8 ]
swapAt() Syntax
The syntax of the array swapAt() method is:
array.swapAt(index1: Int, index2: Int)
Here, array is an object of the Array class.
swapAt() Parameters
The swapAt() method takes two parameters:
- index1 - index of the first element to swap
- index2 - index of the second element to swap
swapAt() Return Value
The swapAt() method doesn't return any value. It only swaps elements of the current array.
Example 1: Swift Array swapAt()
var languages = ["Swift", "C", "Java"]
// swap "C" and "Java"
languages.swapAt(1, 2)
print(languages)
var priceList = [12, 21, 35]
// swap 12 and 35
priceList.swapAt(0,2)
print(priceList)
Output
["Swift", "Java", "C"] [35, 21, 12]
Here,
- For the languages array, we have swapped the elements of index 1 and index 2.
- Similarly, for the priceList array, we have swapped the elements of index 0 and index 2.
Did you find this article helpful?