Swift Tutorial
Swift Data Types
Swift Control Flow
Swift Functions
Swift Collections
Swift OOPs
Swift Additional Topics
In Swift, if you want to swap two items in an array at specific indices, you can use the swapAt(_:_:)
method provided by the Array
type.
Here's how you can do it:
var numbers = [1, 2, 3, 4, 5] // Swap the items at index 1 and 3 (swap 2 with 4) numbers.swapAt(1, 3) print(numbers) // [1, 4, 3, 2, 5]
In this example, we've swapped the number 2
at index 1
with the number 4
at index 3
.
Ensure the indices provided are within the range of the array's indices; otherwise, a runtime crash will occur.
Swift swap array elements:
swapAt(_:_:)
method.var numbers = [1, 2, 3, 4, 5] numbers.swapAt(1, 3) print(numbers) // Output: [1, 4, 3, 2, 5]
How to exchange elements in Swift array:
swapAt(_:_:)
method.var letters = ["A", "B", "C", "D"] letters.swapAt(0, 2) print(letters) // Output: ["C", "B", "A", "D"]
Swift array swap method:
swapAt(_:_:)
method is the primary method for swapping elements in a Swift array.var fruits = ["Apple", "Banana", "Orange"] fruits.swapAt(0, 2) print(fruits) // Output: ["Orange", "Banana", "Apple"]
Swapping array elements in Swift example:
swapAt(_:_:)
method, which takes the indices of the elements to be swapped.var names = ["Alice", "Bob", "Charlie"] names.swapAt(0, 2) print(names) // Output: ["Charlie", "Bob", "Alice"]
Reorder array items in Swift:
var colors = ["Red", "Green", "Blue"] colors.swapAt(1, 2) print(colors) // Output: ["Red", "Blue", "Green"]
Change position of array elements in Swift:
swapAt(_:_:)
method.var animals = ["Dog", "Cat", "Bird"] animals.swapAt(0, 1) print(animals) // Output: ["Cat", "Dog", "Bird"]
Swift array exchange positions:
swapAt(_:_:)
method.var cities = ["New York", "Los Angeles", "Chicago"] cities.swapAt(1, 2) print(cities) // Output: ["New York", "Chicago", "Los Angeles"]
Swap two elements in array Swift:
swapAt(_:_:)
method.var items = ["Item1", "Item2", "Item3"] items.swapAt(0, 1) print(items) // Output: ["Item2", "Item1", "Item3"]
Shuffle and swap array items in Swift:
var numbers = [1, 2, 3, 4, 5] numbers.shuffle() print(numbers) // Output: Randomized order of elements