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:57

There's also stride to generate a reversed index:

let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]

var reversed = [String]()

for index in (names.count - 1).stride(to: -1, by: -1) {
    reversed.append(names[index])
}

It also works well with map:

let reversed = (names.count - 1).stride(to: -1, by: -1).map { names[$0] }

Note: stride starts its index at 1, not at 0, contrary to other Swift sequences.

However, to anyone reading this in the future: use .reverse() instead to actually reverse an array, it's the intended way.

查看更多
男人必须洒脱
3楼-- · 2020-01-31 01:57

Like this, maybe:

names = names.enumerate().map() { ($0.index, $0.element) }.sort() { $0.0 > $1.0 }.map() { $0.1 }

Oh, wait.. I have to use for loop, right? Then like this probably:

for (index, name) in names.enumerate().map({($0.index, $0.element)}).sort({$0.0 > $1.0}).map({$0.1}).enumerate() {
    names[index] = name
}
查看更多
我只想做你的唯一
4楼-- · 2020-01-31 01:57

Here is the most simpler way.

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

var reversedNames = [String]()

for name in names {
    reversedNames.insert(name, at: 0)
}
查看更多
登录 后发表回答