Home > Back-end >  Array Of Years in SwiftUI
Array Of Years in SwiftUI

Time:05-17

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?

CodePudding user response:

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

CodePudding user response:

Use

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