w3resource

Swift Array Programming Exercises: Create a new array with the elements in reverse order of a given array of integers

Swift Array Programming: Exercise-6 with Solution

Write a Swift program to create a new array with the elements in reverse order of a given array of integers .

/*Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.*/

Pictorial Presentation:

Swift Array Programming Exercises: Create a new array with the elements in reverse order of  a given array of integers

Sample Solution:

Swift Code:

func rotate_left_3(_ arra: [Int]) -> [Int] {
    var new_arra = arra
    new_arra.removeFirst()
    new_arra.append(arra.first!)
    return new_arra
}
print(rotate_left_3([1, 2, 3]))
print(rotate_left_3([-1, 0, 1]))

Sample Output:

[2, 3, 1]
[0, 1, -1]

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to rotate the elements of an array of integers to left direction.
Next: Write a Swift program to find the larger value of an given array of integers and set all the other elements with that value.

What is the difficulty level of this exercise?



Inviting useful, relevant, well-written and unique guest posts