arrayssortingstructswiftuiexternal-sorting

SwiftUI Sort array of custom objects by id


//Person Struct

struct Person {
            var id: Int
            var age: Int
            var nPerson: [Person]
        }

// Array type of Person

 var persons = [

        Person(id: 123, age: 23, nPerson: []),
        Person(id: 421, age: 45, nPerson: [

            Person(id: 100, age: 13, nPerson: [
            Person(id: 5, age: 23, nPerson: []),
            Person(id: 112, age: 89, nPerson: []),
            ]),
            Person(id: 42, age: 33, nPerson: []),
            Person(id: 112, age: 73, nPerson: []),
            Person(id: 126, age: 23, nPerson: []),

        ]),

        Person(id: 343, age: 5, nPerson: [

            Person(id: 22, age: 109, nPerson: []),
            Person(id: 421, age: 102, nPerson: []),
            Person(id: 141, age: 12, nPerson: []),
            Person(id: 136, age: 54, nPerson: []),

        ])

    ]

I have an object Person inside of person I have id and nPerson, and that nPerson is a type of Person. I want to sort array by the id also that sort would work inside the nPerson array.


Solution

  • You can use Swift in-build sort function to archive this.

    let sortedPersons = persons.sorted {$0.id < $1.id}.map { (person) -> Person in
    
             var tempPerson = person
             let shortednPersons = (person.nPerson).sorted { $0.id < $1.id }
             tempPerson.nPerson = shortednPersons
    
             return tempPerson
    
    }