Reputation: 2834
This link tells you what your sorting function has to look like, but I just can't make a Swift function look like that.
Here's my call:
packetsArray.sortUsingFunction(comparePacketDates, context: nil)
Here's my function, and I've tried a zillion other variations of it:
static func comparePacketDates(packet1 : AnyObject, packet2: AnyObject, context: UnsafeMutablePointer<Void>) -> Int {
And I've tried using a c function instead, this and a few other variations:
NSInteger comparePacketDates(id packet1, id packet2, void* dummy);
It's always "cannot invoke with argument list ..." saying the function isn't what's expected as the first argument.
Does anyone have example code of a Swift function that would be accepted as the first argument of the Swift sortUsingFunction? Or even a c function that would be accepted as the first argument of the Swift SortUsingFunction?
Upvotes: 2
Views: 677
Reputation: 385600
Use sortUsingComparator
. It's simpler than sortUsingFunction
. Here's the syntax:
a.sortUsingComparator {
let packet1 = $0 as! Packet
let packet2 = $1 as! Packet
if packet1.timestamp < packet2.timestamp {
return .OrderedAscending
}
if packet1.timestamp == packet2.timestamp {
return .OrderedSame
}
return .OrderedDescending
}
Upvotes: 4
Reputation: 6524
Here is an example for your reference that I wrote:
var ma = NSMutableArray()
ma.addObject("Hi")
ma.addObject("Anil")
func comp(first: AnyObject, second:AnyObject, context: UnsafeMutablePointer<Void>) -> Int {
let f:String = first as! String
let s:String = second as! String
if f > s {
return 1
}
else if ( f == s ) {
return 0
}
return -1
}
ma.sortUsingFunction(comp, context:UnsafeMutablePointer<Void>(bitPattern: 0))
HTH, as a reference to you. Note: I am in Xcode 7.1 Swift 2.1.
Upvotes: 0