【问题标题】:How to sort an array of object in Swift?如何在 Swift 中对对象数组进行排序?
【发布时间】:2015-06-23 04:55:20
【问题描述】:

我现在是这样写的

static func fromIntervals(intervals: [Interval]) -> ChartData {
    let sortedIntervals = intervals.sorted { (a, b) in return a.startTime < b.startTime}
}

但它显示错误

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

我搜索了很多其他代码示例,但它们都不起作用,我不知道为什么。有什么建议吗?

【问题讨论】:

标签: ios swift


【解决方案1】:

sort不是sorted

let sortedIntervals = intervals.sort { (a, b) in return a.startTime < b.startTime}

【讨论】:

    【解决方案2】:

    你做错了。使用sort 而不是sorted

    static func fromIntervals(intervals: [Interval]) -> ChartData {
        let sortedIntervals = intervals.sort { (a, b) in return a.startTime < b.startTime}
    }
    

    编辑

    let sortedIntervals = sorted(intervals, { (a: Object, b: Object) -> Bool in return a.startTime < b.startTime } )
    

    更多信息请参见Apple's doc

    【讨论】:

    • sort 正在改变间隔本身 - 但这是不可变的,因为它是函数的参数。我想要另一个排序的副本。
    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2019-11-02
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多