我有数组,需要不使用Array.reverse方法而仅通过for循环将其反转。
Array.reverse
for
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
这是@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]) }