0

I have a class called "Man". One of a variable of Man is the "height" of the person.

I have for example 10 objects of "Man" with different values for the height parameter and now I want to order these objects by the height. How can I achieve this?

var allMan:[Man] = [Man]()
    for currentMan in allMan {
        //Something to do
    }
user3143691
  • 1,533
  • 3
  • 11
  • 19

1 Answers1

0

Let us assume that allMen is the array to be sorted:

var allMen = [Man]()

Then, suppose you initialised the array with 10 values. After that you can get sorted allMen in descending order:

var allSortedMen = allMen.sort { $0.height > $1.height }

Explanation:

You should pass a function/closure of the type isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) -> Bool

let sortedAllMen = allMen.sort { (first: Men, second: Men -> Bool in
    return first.height > second.height  
    // or return first.height < second.height for ascending sort order
}
Beraliv
  • 518
  • 7
  • 20