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条回答
▲ chillily
2楼-- · 2020-01-31 01:36

Do it like this for reversed sorting.

 let unsortedArray: [String] = ["X", "B", "M", "P", "Z"]
        // reverse sorting
        let reversedArray = unsortedArray.sorted() {$0 > $1}

        print(reversedArray) // ["Z", "X", "P", "M", "B"]
查看更多
疯言疯语
3楼-- · 2020-01-31 01:36

I like simple codes.

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

var reversedNames = [""]

for name in names {
    reversedNames.insert(name, at: 0)
}

print(reversedNames)
查看更多
该账号已被封号
4楼-- · 2020-01-31 01:36
var arr = [1, 2, 3, 4, 5]   // Array we want to reverse
var reverse: [Int]!      // Array where we store reversed values

reverse = arr

for i in 0...(arr.count - 1) {

    reverse[i] = arr.last!  // Adding last value of original array at reverse[0]
    arr.removeLast()        // removing last value & repeating above step.
}

print("Reverse : \(reverse!)")

A more simple way :)

查看更多
唯我独甜
5楼-- · 2020-01-31 01:42

Swift 3:

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

var reversedNames : [String] = Array(names.reversed())

print(reversedNames)  // ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]
查看更多
不美不萌又怎样
6楼-- · 2020-01-31 01:42

Here is how I did it and there is no warning for Swift 3

let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()

for name in names.enumerate() {
  let newIndex = names.count - 1 - name.index
  reversedNames.append(names[newIndex])
}

or just simply

reversedNames = names.reverse()
查看更多
小情绪 Triste *
7楼-- · 2020-01-31 01:42

You can use the swift3 document:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversedNames = names.sorted(by: >)

// reversedNames is equal to:
//   ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
查看更多
登录 后发表回答