2

I have an array of structs. In the struct I have two NSDate objects: prop1 and prop2. I'm trying to sort prop1 from newest to oldest date/time. And I want prop2 to also get ordered based on prop1. (I will also want to do vice versa.)

struct Item {
    let prop1 : NSDate
    let prop2 : NSDate
}

var myItem = [Item]()

myItem.insert(Item(prop1: myDateSecond, prop2: anotherDateSecond), atIndex: 0)
myItem.insert(Item(prop1: myDateThird, prop2: anotherDateThird), atIndex: 0)
myItem.insert(Item(prop1: myDateFirst, prop2: anotherDateFirst), atIndex: 0)

myItem.sort { $0.prop1 < $1.prop1 }

At the last line of code, I get the following error:

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

What am I doing wrong, and how can I fix it?

2
  • What's array in array.sort? Commented Aug 31, 2015 at 2:07
  • My bad. I just changed it to myItem.sort Commented Aug 31, 2015 at 2:10

1 Answer 1

1

When comparing two dates you have to use NSDate method compare:

struct Item {
    let prop1 : NSDate
    let prop2 : NSDate
}

var myItem = [Item]()

myItem.insert(Item(prop1: myDateSecond, prop2: anotherDateSecond), atIndex: 0)
myItem.insert(Item(prop1: myDateThird, prop2: anotherDateThird), atIndex: 0)
myItem.insert(Item(prop1: myDateFirst, prop2: anotherDateFirst), atIndex: 0)

myItem.sort{$0.prop1.compare($1.prop1) == NSComparisonResult.OrderedAscending}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer! Can you please include the longer version of sort? This one is a bit confusing and hard to read. Thanks!
Thats basic Swift syntax. I've posted the documentation's link to the compare method.
I'm talking about $0.prop1.compare($1.prop2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.