To rotate elements in an array using Swift, you can implement a custom rotation function that shifts elements by a specified number of positions.
In this example,
intArray
containing integers.rotate
function that shifts elements by a specified number of positions.var intArray = [1, 2, 3, 4, 5]
let positions = 2
func rotateArray(_ array: inout [Int], _ positions: Int) {
let n = array.count
let p = positions % n
array = Array(array.reversed())
array[0..<p] = array[0..<p].reversed()
array[p..<n] = array[p..<n].reversed()
}
rotateArray(&intArray, positions)
print("Rotated Array:", intArray)
Rotated Array: [4, 5, 1, 2, 3]
In this example,
strArray
containing strings.rotate
function that shifts elements by a specified number of positions.var strArray = ["apple", "banana", "cherry", "date", "fig"]
let positions = 3
func rotateArray(_ array: inout [String], _ positions: Int) {
let n = array.count
let p = positions % n
array = Array(array.reversed())
array[0..<p] = array[0..<p].reversed()
array[p..<n] = array[p..<n].reversed()
}
rotateArray(&strArray, positions)
print("Rotated Array:", strArray)
Rotated Array: ["date", "fig", "apple", "banana", "cherry"]
In this tutorial, we learned How to Rotate Elements in an Array in Swift language with well detailed examples.