我有一个列表需要按“受欢迎程度”(从流行到不流行)进行排序,该值来自JSON API。 SwiftUI中是否有给定值的排序功能?
JSON如下:
[
{
"id": 1,
"nombre": "The design of every day things",
"autor": "Don Norman",
"disponibilidad": true,
"popularidad": 70,
"imagen": "https://images-na.ssl-images-amazon.com/images/I/410RTQezHYL._SX326_BO1,204,203,200_.jpg"
},
{
"id": 2,
"nombre": "100 años de soledad",
"autor": "Garcia Marquez",
"disponibilidad": false,
"popularidad": 43,
"imagen": "https://images-na.ssl-images-amazon.com/images/I/51egIZUl88L._SX336_BO1,204,203,200_.jpg"
}
]
还有更多,仅仅是一部分。
受欢迎程度为popularidad
。
这是我目前的列表:
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .leading) {
ForEach(booksVM.books) { book in
HStack {
Text(book.nombre)
Spacer()
}
Text(book.autor)
Spacer()
}
}.padding(.leading, 5)
}
.navigationBarTitle("Bienvenido a la librería flux")
.onAppear(perform: self.booksVM.fetchBooks)
}
}
请让我知道是否需要更多代码来理解这一点。
答案 0 :(得分:1)
您可以使用.sorted
对数组进行排序。
这是一个使用数据的简单示例。如果在操场上尝试,这将起作用。
let data = """
[
{
"id": 1,
"nombre": "The design of every day things",
"autor": "Don Norman",
"disponibilidad": true,
"popularidad": 70,
"imagen": "https://images-na.ssl-images-amazon.com/images/I/410RTQezHYL._SX326_BO1,204,203,200_.jpg"
},
{
"id": 2,
"nombre": "100 años de soledad",
"autor": "Garcia Marquez",
"disponibilidad": false,
"popularidad": 43,
"imagen": "https://images-na.ssl-images-amazon.com/images/I/51egIZUl88L._SX336_BO1,204,203,200_.jpg"
}
]
""".data(using: .utf8)!
struct Book: Codable {
let id: Int
let popularidad: Int
let nombre: String
let autor: String
let disponibilidad: Bool
let imagen: String
}
let decoder = JSONDecoder()
let books = try decoder.decode([Book].self, from: data)
let result = books.sorted {
$0.popularidad > $1.popularidad
}
print(result)
在使用ForEach
因此,您所需要做的就是对Book
对象数组进行排序。
ForEach(booksVM.books.sorted { $0.popularidad > $1.popularidad}) { book in