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

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

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

回答:

这是@Abhinav的答案翻译为 :

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循环或使用的任何错误或警告--

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

}

以上是 如何在Swift中不使用“ .reverse()”来反转数组? 的全部内容, 来源链接: utcz.com/qa/417545.html

回到顶部