Tobias Weidler
Tobias Weidler

Reputation: 41

How can I make an instance conform to "Comparable"?

enter image description hereDid somebody have an idea how can I fix this?

In the following Line:

//Entry Image Shared   
for shared in entryImagepostShared.sorted() {
    postetImageShared.append(shared)
}

I get an Error Like: Referencing instance method sorted() on Sequence requires that Bool conform to Comparable

postetImages.removeAll()
postetImageComment.removeAll()
postetImageID.removeAll()
postetImageShared.removeAll()
                
for document in snapshot!.documents {
                    
    guard let entryImageURL = document["imageURL"] as? [String],
    let entryImageComment = document["postText"] as? [String],
    let entryImagepostShared = document["postShared"] as? [Bool] else { return }
                    
     //Entry Image URL's
         for url in entryImageURL.sorted() {
             postetImages.append(url)
             }
         let count = postetImageURL.count
         imageURLCount += count
                    
         //Entry Image Comment
          for comment in entryImageComment.sorted() {
              postetImageComment.append(comment)
           }
                    
          //Entry Image Shared
          for shared in entryImagepostShared.sorted() {
              postetImageShared.append(shared)
          }
                    
      }

Upvotes: 1

Views: 1774

Answers (1)

Vadim Belyaev
Vadim Belyaev

Reputation: 2859

The Array's method sorted() requires that the array's values are comparable, i.e. there's a way to tell whether one value is less than another.

By default, the type Bool does not have this behavior.

If you need to sort an array of Bools, first you need to decide whether you want to see the false values first or the true values first.

Assuming the former, here are two ways to achieve this:

  1. Use the sorted(by:) method which takes a closure. This closure takes two values and returns a Bool that indicates whether they are in increasing order:
let sorted = arrayOfBools.sorted { $0 == false || $1 == true }
  1. Make the Bool conform to Comparable by implementing your own extension. Then you can just use sorted():
extension Bool: Comparable {
    public static func < (lhs: Bool, rhs: Bool) -> Bool {
        lhs == false || rhs == true
    }
}

let sorted1 = arrayOfBools.sorted()

Upvotes: 1

Related Questions