xcode - 无法使用排序函数 swift 找到重载

标签 xcode swift overloading sorting

我正在尝试根据 listTitle 属性按字母顺序对 List 对象数组进行排序。这是我的 List 对象:

class List : DBObject   {

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

这是我的排序函数:

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()

}

sortedLists 行上,我收到错误:

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

任何和所有帮助将不胜感激。

最佳答案

NSString没有<开箱即用:

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?

对于隐式 NSString 来说,这过去不是什么问题。至String转换,但 1.2 取消了这一点。

有多种不同的方法可以解决此问题,但请尝试:

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

顺便说一句,数组有 sorted内置方法(可能会执行得更好,因为它更了解它正在排序的内容):

let sortedLists = listArray.sorted { etc. }

此外,每当您发现自己创建了一个空数组,然后用另一个序列的每个元素的转换来填充它时,这都是 map 的一个很好的候选者。 :

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

关于xcode - 无法使用排序函数 swift 找到重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29745265/

相关文章:

xcode - 苹果软件版本命名约定

ios - 在 Objective-C 中声明 ImageView 的另一种方法

swift - 在 Swift 中,返回相同类型函数的通用函数给我 "Cannot explicitly specialize a generic function"

c++ - 有没有办法仅通过名称来检测重载的成员函数? (不检测名称)

ios - 推送 View Controller 不显示从 Storyboard添加的元素

ios - NSBundle实例方法URLForResource :withExtension returning invalid CFStringRef on device

arrays - Swift 可选数组属性是不可变的?

swift - 将 Double 转换为数字数组

c++ - 用另一个类的函数重载一个函数

c++ - 虚函数重载