How to Reverse an Array in Swift

How to reverse array in Swift without using .reverse()?

Here is @Abhinav 's answer translated to Swift 2.2 :

var names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]

var reversedNames = [String]()

for arrayIndex in (names.count - 1).stride(through: 0, by: -1) {
reversedNames.append(names[arrayIndex])
}

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:

let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]

var reversedNames = [String]()

for arrayIndex in stride(from: names.count - 1, through: 0, by: -1) {
reversedNames.append(names[arrayIndex])
}

Alternatively, you could loop through normally and subtract each time:

let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]

let totalIndices = names.count - 1 // We get this value one time instead of once per iteration.

var reversedNames = [String]()

for arrayIndex in 0...totalIndices {
reversedNames.append(names[totalIndices - arrayIndex])
}

How to reverse an array in Swift?

Here is code for swift 3

let array = ["IOS A", "IOS B", "IOS C"]
for item in array.reversed() {
print("Found \(item)")
}

Reverse an array in Swift

Try this:

var newArray = Array(array.reversed())

array.reversed() returns a structure of type ReversedCollection that you can use to initialise an actual array with Array().

How to reverse a integer array in swift

use ab.reversed() function which returns a reversed array.

Why does the reverse() function in the Swift standard library return ReverseRandomAccessCollection?

It is an performance optimization for both time and memory.
The ReverseRandomAccessCollection presents the elements of the
original array in reverse order, without the need to create a new array
and copying all elements (as long as the original array is not
mutated).

You can access the reversed elements with subscripts:

let el0 = arr[arr.startIndex]
let el2 = arr[arr.startIndex.advancedBy(2)]

or

for i in arr.indices {
print(arr[i])
}

You can also create an array explicitly with

let reversed = Array(["Mykonos", "Rhodes", "Naxos"].reversed())

A dictionary is also a sequence of Key/Value pairs. In

let dict = ["greek" : "swift sometimes", "notgreek" : "ruby for this example"].reverse()

a completely different reversed() method is called:

extension SequenceType {
/// Return an `Array` containing the elements of `self` in reverse
/// order.
///
/// Complexity: O(N), where N is the length of `self`.
@warn_unused_result
public func reversed() -> [Self.Generator.Element]
}

The result is an array with the Key/Value pairs of the dictionary
in reverse order. But this is of limited use because the order
of the Key/Value pairs in a dictionary can be arbitrary.

Reverse a for loop of an array

As the name implies you can reverse an array just with reversed().

Your code is rather objective-c-ish. A better way to enumerate the array is fast enumeration because you actually don't need the index.

for coord in arrayLocations { ...

and

for coord in arrayLocations.reversed() { ...

However there is a still swiftier way mapping the arrays

func createCoordinatePoly() {
arrayLocationOffset.append(contentsOf: arrayLocations.map{coord270(coord: $0)})
arrayLocationOffset.append(contentsOf: arrayLocations.reversed().map{coord90(coord: $0)})
debugPrint("aggiunto array poly \(arrayLocationOffset.count)")
}

Reverse Array of coordinates in swift 4

There may be a more elegant/efficient way to do this, but I'd look at using compactMap:

let testArray = [[1.123,2.22], [3.11, 4.0], [5.21, 6.19]]
print(testArray)

[[1.123, 2.22], [3.11, 4.0], [5.21, 6.19]]

let flippedElementArray = testArray.compactMap { $0.count > 1 ? [$0[1], $0[0]] : nil }
print(flippedElementArray)

[[2.22, 1.123], [4.0, 3.11], [6.19, 5.21]]

The $0.count > 1 check just makes sure you have at least 2 elements so you don't get a bounds error. If not, the closure returns nil for that element, which will be filtered out by compactMap. Otherwise, it returns a new array element consisting of the second element followed by the first element. All of those elements are stored in the final mapped array (flippedElementArray).

Reverse an array of integers without using Swift's object properties/methods

With tuples

func reverse(array: inout [Int], count: Int) {
if count < 2 { return }
var first = 0
var last = count - 1
while first < last {
(array[first], array[last]) = (array[last], array[first])
first += 1
last -= 1
}
}

Without tuples

func reverse(array: inout [Int], count: Int) {
func swapAt(_ firstIndex: Int, _ secondIndex: Int) {
let firstValue = array[firstIndex]
array[firstIndex] = array[secondIndex]
array[secondIndex] = firstValue
}

if count < 2 { return }
var first = 0
var last = count - 1
while first < last {
swapAt(first, last)
first += 1
last -= 1
}
}


Related Topics



Leave a reply



Submit