Search code examples
iosarraysswiftnsmutablearraycolumnsorting

Swift - Sorting NSMutableArray with objects in it


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.


Solution

  • 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