小编典典

如何在Swift中不使用“ .reverse()”来反转数组?

swift

我有数组,需要不使用Array.reverse方法而仅通过for循环将其反转。

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

阅读 604

收藏
2020-07-07

共1个答案

小编典典

这是@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])
}

使用此代码不会给您有关不赞成使用C样式for循环或使用的任何错误或警告--

Swift 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])
}

另外,您可以正常循环并每次减去:

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])
}
2020-07-07