【问题标题】:How can I sort an array of Bus objects by their bus number (buses.number)? [duplicate]如何按总线编号(buses.number)对总线对象数组进行排序? [复制]
【发布时间】:2017-01-18 02:52:54
【问题描述】:

假设我有以下 Bus 对象数组:

var buses = [Bus]()

总线数组填满后,我想按总线编号(例如“501”的字符串)对总线数组进行排序。每个 Bus 对象都有一个总线编号(buses[index].number)。没有重复的巴士号码。我该怎么做?我看到了过滤器,但我不确定如何应用它。

【问题讨论】:

    标签: ios swift sorting


    【解决方案1】:

    sort method in swift 就是这么简单,

    let sortedBuses = buses.sort({ $0.number > $1.number })
    

    buses.sortInPlace({ $0.number > $1.number }) // this sorts arrays and saves it in self.
    

    【讨论】:

    • 太棒了,谢谢。我会在 7 分钟内接受答案。
    • 请记住,如果numberString,那么这将进行字母排序,而不是数字排序。换句话说,例如,200 路公交车将在 8 路公交车之前到达。
    • 我应该使用 sortInPlace 而不是 sort 吗? Xcode 给了我一个警告。
    • 使用闭包排序,但要注意 swift 版本。 Swift 2.3 -> sort 返回排序后的数组,但 sortInPlace 排序相同的数组 Swift 3.0 -> sorted 返回排序后的数组,但 sort 排序相同的数组
    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2020-05-18
    • 2021-12-16
    • 1970-01-01
    • 2013-12-01
    相关资源
    最近更新 更多