sorting dictionary based on two constraints

I am trying to sort the values in a dictionary (Word objects) based on two constraints. The Word objects have two relevant fields: Int: count and Bool: pinned. These constraints are as follows: first if the word is pinned (i.e. value.pinned = true), I want the word to appear first in the sorted array regardless of its count field. If the word is not pinned, then I want the word to be sorted based on its count value among other unpinned words in decreasing order.

I ended up implementing the sorting function like this:

sortedWordsArr = wordsDict.sorted {
                        if $0.value.pinned{
                            return $0.value.pinned && !$1.value.pinned
                        }
                        
                        else{
                            return $0.value.count > $1.value.count
                        }
                    }

However, this does not seem to do the job. When I pin words, they don't move to the beginning of the array. They seem to shuffle around randomly, and sometimes not at all. I've browsed forums that seem to answer this question of how to sort using multiple constraints, but I'm still not too sure how to set the sorted closure up for my constraints.

It seems to me that this first condition: return $0.value.pinned && !$1.value.pinned compares a pinned word $0 to a not necessarily pinned object $1 since $1 is just specified to be another word, not necessarily a pinned one in my dictionary. Is this line of thought incorrect? If so, how can I sort my dictionary correctly based on these constraints?

Thank you for reading this post- appreciative of any help!



from Recent Questions - Stack Overflow https://ift.tt/3fn7BqL
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations