SwiftUI 中的一系列年份

Array Of Years in SwiftUI

我正在使用 的数组,范围 1950...2022.

这是我的代码:

let years = (1950...2022).map() { String([=10=]) }

但是我必须按照 2022...1950 这样的降序排列,如果我写

let years = (2022...1950).map() { String([=11=]) }

这给我以下错误:

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

有谁知道如何按降序顺序获取它?

你应该使用reversed

(1950...2022).reversed().map({ String([=11=]) }

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

或者您可以使用 stride

stride(from: 2022, through: 1950, by: -1).map({ String([=13=]) })

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

使用

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