Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list in SwiftUI using JSON

Tags:

swiftui

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.

like image 768
haweg Avatar asked Nov 06 '19 15:11

haweg


People also ask

How do I sort in ascending order in Swift?

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.

How do you sort an array of data in Swift?

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.


1 Answers

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
like image 94
Andrew Avatar answered Oct 23 '22 18:10

Andrew