如何在不使用".reverse()"的情况下在Swift中反转数组?

Mil*_*dic 19 arrays swift

我有数组,需要在没有Array.reverse方法的情况下反转它,只有for循环.

var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
Run Code Online (Sandbox Code Playgroud)

use*_*776 13

斯威夫特3:

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

var reversedNames : [String] = Array(names.reversed())

print(reversedNames)  // ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]
Run Code Online (Sandbox Code Playgroud)


ZGs*_*ski 12

这是@Abhinav的答案翻译成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])
}
Run Code Online (Sandbox Code Playgroud)

使用此代码不应该给出任何关于C-style for-loops的弃用或使用的错误或警告--.

斯威夫特3:

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])
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以正常循环并每次减去:

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])
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,您也可以将它与一个map混合成let letededNames =(names.count-1).stride(through:0,by:-1).map {names [$ 0]} 该解决方案实际上在[Eric的答案](http://stackoverflow.com/a/33463720/669586)中。 (2认同)

bru*_*sas 9

¿这是必须的for吗?如果没有,你可以使用reduce.

我想这是没有reverse()方法(Swift 3.0.1)实现它的最短路径:

["Apple", "Microsoft", "Sony", "Lenovo", "Asus"].reduce([],{ [$1] + $0 })
Run Code Online (Sandbox Code Playgroud)


Mik*_*ico 5

只需要让(names.count/2) 通过数组。无需声明临时变量,在进行交换时……它是隐式的。

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"]
Run Code Online (Sandbox Code Playgroud)