'Array Of Years in SwiftUI

I am using an array of years ranged 1950...2022.

This is my code to get this:

let years = (1950...2022).map() { String($0) }

But I have to go in descending order like 2022...1950, and if I write

let years = (2022...1950).map() { String($0) }

This is giving me the following error:

Thread 1: Fatal error: Range requires lowerBound <= upperBound

Did anyone knows how to get it in descending order?



Solution 1:[1]

You should use reversed

(1950...2022).reversed().map({ String($0) }

https://developer.apple.com/documentation/swift/array/1690025-reversed

Or you can use stride

stride(from: 2022, through: 1950, by: -1).map({ String($0) })

https://developer.apple.com/documentation/swift/1641347-stride

Solution 2:[2]

Use

let arr = Array(stride(from: 2022, to: 1950, by: -1))
print(arr)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sh_Khan