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
    }
1

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.