How to reverse array in Swift without using “.reve

2020-01-31 01:28发布

I have array and need to reverse it without Array.reverse method, only with a for loop.

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

标签: arrays swift
21条回答
等我变得足够好
2楼-- · 2020-01-31 01:44

Do you really need a for loop? If not, you can use reduce.

I guess that this is the shortest way to achieve it without reversed() method (Swift 3.0.1):

["Apple", "Microsoft", "Sony", "Lenovo", "Asus"].reduce([],{ [$1] + $0 })
查看更多
小情绪 Triste *
3楼-- · 2020-01-31 01:49

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"]
查看更多
女痞
4楼-- · 2020-01-31 01:52

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)
查看更多
Emotional °昔
5楼-- · 2020-01-31 01:53

Here the code for swift 3

let array = ["IOS A", "IOS B", "IOS C"]
    for item in array.reversed() {
    print("Found \(item)")
    }
查看更多
forever°为你锁心
6楼-- · 2020-01-31 01:53

Here is @Abhinav 's answer translated to 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])
}

Using this code shouldn't give you any errors or warnings about the use deprecated of C-style for-loops or the use of --.

Swift 3 - Current:

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

Alternatively, you could loop through normally and subtract each time:

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])
}
查看更多
我想做一个坏孩纸
7楼-- · 2020-01-31 01:57

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])
}
查看更多
登录 后发表回答