-1

I have a fruit object in swift with

var title: String? 
var desc: String?

variables

I have it in a fruitsArray which is an NSMutableArray.

I want to sort out these fruit objects alphabetically depending on their title. I need to do this both ascending and descending.

I have tried doing the following:

 NSSortDescriptor *sortDescriptor =
        [NSSortDescriptor sortDescriptorWithKey:@"title"
    ascending:YES
    selector:@selector(caseInsensitiveCompare:)];
    [fruitsArray sortedArrayUsingDescriptors:@[sortDescriptor]];

But it does not work at all, just heaps of errors.

How do I do this?

Thanks in advance friends.

BWA
  • 5,314
  • 7
  • 29
  • 42
Big Green Alligator
  • 1,015
  • 2
  • 16
  • 30

2 Answers2

0

You have to use sort function with a block:

struct Fruit {
    var title: String
    var desc: String
}

var fruits = [Fruit]()
fruits.append(Fruit(title: "a", desc: "b"))
fruits.append(Fruit(title: "c", desc: "d"))


let sorted = fruits.sort() { $0.title > $1.title }
sorted
Arsen
  • 10,215
  • 2
  • 30
  • 41
0

it should be sortUsingDescriptors: not sortedArrayUsingDescriptors:

iOS77
  • 492
  • 5
  • 3