I have a list that I need to sort by "popularity" (more popular to less popular), this value comes from a JSON API. Is there a Sort function by given value in SwiftUI?
The JSON looks like this:
[
{
"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"
}
]
There's more to it, that's just a piece of it.
Popularity is popularidad
.
This is currently my list:
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)
}
}
Please let me know if more code is needed to understand this.
Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator ( < ). To sort the elements of your collection in descending order, pass the greater-than operator ( > ) to the sort(by:) method.
To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.
You could use .sorted
to sort your array.
Here is a simple example using your data. This will work if you try it in a playground.
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)
You would just have to perform your sort before you use the array of books in the ForEach
So all you have to do is the following which will sort your array of Book
objects.
ForEach(booksVM.books.sorted { $0.popularidad > $1.popularidad}) { book in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With