I have array and need to reverse it without Array.reverse
method, only with a for
loop.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
I have array and need to reverse it without Array.reverse
method, only with a for
loop.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
Do you really need a
for
loop? If not, you can usereduce
.I guess that this is the shortest way to achieve it without reversed() method (Swift 3.0.1):
Only need to make (names.count/2) passes through the array. No need to declare temporary variable, when doing the swap...it's implicit.
This will work with any sized array.
Here the code for swift 3
Here is @Abhinav 's answer translated to Swift 2.2 :
Using this code shouldn't give you any errors or warnings about the use deprecated of C-style for-loops or the use of
--
.Swift 3 - Current:
Alternatively, you could loop through normally and subtract each time:
Here you go: