How to reverse array in Swift without using ".reverse()"? -
i have array , need reverse without array.reverse
method, for
loop.
var names:[string] = ["apple", "microsoft", "sony", "lenovo", "asus"]
here @abhinav 's answer translated swift 2.2 :
var names: [string] = ["apple", "microsoft", "sony", "lenovo", "asus"] var reversednames = [string]() arrayindex in (names.count - 1).stride(through: 0, by: -1) { reversednames.append(names[arrayindex]) }
using code shouldn't give errors or warnings use deprecated of c-style for-loops or use of --
.
swift 3:
var names: [string] = ["apple", "microsoft", "sony", "lenovo", "asus"] var reversednames = [string]() arrayindex in stride(from: names.count - 1, through: 0, by: -1) { reversednames.append(names[arrayindex]) }
alternatively, loop through , subtract each time:
var names: [string] = ["apple", "microsoft", "sony", "lenovo", "asus"] var reversednames = [string]() arrayindex in 0..<names.count { reversednames.append(names[(names.count - 1) - arrayindex]) }
Comments
Post a Comment