Unable to sort Swift array

I'm trying to sort contacts array by severity

  var contacts: [Contact]? if let customer = CoreDataAccess.sharedInstance.getSavedCustomer() { //Cast from NSSet to [Contact] self.contacts = customer.contacts.allObjects as? [Contact] self.contacts!.sort({$0.severity < $1.severity}) //error } 

Compiler error in the marked line with the following message:

 Cannot invoke 'sort' with an argument list of type '((_, _) -> _)' 

I am not sure what I am doing wrong, because it works the same in another file. If this helps explain, the above code crashes when working on the WatchKit interface, but not when using it on iOS.

EDIT: NSNumber is NSNumber

+4
source share
3 answers

Try to cast the first argument to NSNumber and use the compare: method (I checked it on the playground)

 var contacts: [Contact]? if let customer = CoreDataAccess.sharedInstance.getSavedCustomer() { //Cast from NSSet to [Contact] self.contacts = customer.contacts.allObjects as? [Contact] self.contacts!.sort { ($0.severity as NSNumber).compare($1.severity) == .orderedAscending } } 

If possible, use Int rather than NSNumber

It is even more efficient to declare a relation as its own Swift Set<Contact> and an attribute as Int , this avoids calling allObjects and type casts.

 var contacts: [Contact]? if let customer = CoreDataAccess.sharedInstance.getSavedCustomer() { self.contacts = customer.contacts.sorted { $0.severity < $1.severity } } 
+2
source

I think the problem is the β€œseriousness” of the contact!

The severity type is your custom type, and it does not implement the comparison operator of type "<"

Since severity is NSNumber, we can do it.

 func <(lhs: NSNumber, rhs: NSNumber) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedSame } 

then the code will work fine.

+1
source

Try the following:

 var contacts: [Contact]? if let customer = CoreDataAccess.sharedInstance.getSavedCustomer() { //Cast from NSSet to [Contact] self.contacts = customer.contacts.allObjects as? [Contact] self.contacts!.sort { $0.severity < $1.severity } } 
0
source

All Articles