Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 234 Vote(s) - 3.42 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to reverse array in Swift without using ".reverse()"?

#21
Here is how I did it and there is no warning for Swift 3

let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()

for name in names.enumerate() {
let newIndex = names.count - 1 - name.index
reversedNames.append(names[newIndex])
}

or just simply

reversedNames = names.reverse()
Reply

#22

Only need to make (names.count/2) passes through the array. No need to declare temporary variable, when doing the swap...it's implicit.

var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
let count = names.count
for i in 0..<count/2 {
(names[i],names[count - i - 1]) = (names[count - i - 1],names[i])
}
// Yields: ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]

Reply

#23
This will work with any sized array.

import Cocoa

var names:[String] = [ "A", "B", "C", "D", "E","F"]
var c = names.count - 1
for i in 0...(c/2-1) { swap(&names[i],&names[c-i]) }

print(names)

Reply

#24
There's also `stride` to generate a reversed index:

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

var reversed = [String]()

for index in (names.count - 1).stride(to: -1, by: -1) {
reversed.append(names[index])
}

It also works well with `map`:

let reversed = (names.count - 1).stride(to: -1, by: -1).map { names[$0] }

*Note: `stride` starts its index at 1, not at 0, contrary to other Swift sequences.*

However, to anyone reading this in the future: **use `.reverse()`** instead to actually reverse an array, it's the intended way.
Reply

#25
Here you go:

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

var reversedNames = [String]()

for var arrayIndex = names.count - 1 ; arrayIndex >= 0 ; arrayIndex-- {
reversedNames.append(names[arrayIndex])
}
Reply

#26
Like this, maybe:

names = names.enumerate().map() { ($0.index, $0.element) }.sort() { $0.0 > $1.0 }.map() { $0.1 }

Oh, wait.. I *have* to use `for` loop, right? Then like this probably:

for (index, name) in names.enumerate().map({($0.index, $0.element)}).sort({$0.0 > $1.0}).map({$0.1}).enumerate() {
names[index] = name
}


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through