Jacob King
Jacob King

Reputation: 6157

Cannot find overload with sorted function swift

Am trying to sort an array of List objects based on their listTitle property in alphabetical order. Here is my List object:

class List : DBObject   {

    dynamic var listTitle : NSString!
    dynamic var listDate : NSDate!
    dynamic var ordered : NSNumber!
    dynamic var qrCode : NSString!
    dynamic var storeId : NSNumber!    
}

and here is my sort function:

func sortByName()   {

    var listArray = [List]()

    for object in cardViewArray {
        let card = object as CardView
        listArray.append(card.list)
    }

    var sortedLists = [List]()
    sortedLists = sorted(listArray) { $0.listTitle < $1.listTitle }
    reloadView()

}

On the sortedLists line I'm getting the error :

'Cannot find an overload for 'sorted' that accepts an argument list of type '([(List)], (_, _) -> _)''.

Any and all help would be appreciated.

Upvotes: 2

Views: 1115

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40963

NSString doesn’t have a < out of the box:

let s1: NSString = "foo"
let s2: NSString = "bar"

s1 < s2
// error: 'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?

This used to be less of a problem with the implicit NSString to String conversion, but 1.2 nixed that.

Various different ways to fix this, but try:

sorted(listArray) { ($0.listTitle as String) < ($1.listTitle as String) }

By the way, arrays have a sorted method built in (which may perform better, since it knows more about what it’s sorting):

let sortedLists = listArray.sorted { etc. }

Also, whenever you find yourself creating an empty array, then populating it with a transformation of every element of another sequence, that’s a good candidate for map:

let listArray = cardViewArray.map { 
    let card = $0 as CardView
    return card.list
}

Upvotes: 2

Related Questions