【问题标题】:Move specific array elements to the end in Swift在 Swift 中将特定的数组元素移动到末尾
【发布时间】:2021-09-11 12:17:00
【问题描述】:

我有一个对象数组,比如看起来像这样的联系人

class Contact {
    var name: String
    var status: Status
    
    init(name: String, status: Status) {
        self.status = status
        self.name = name
    }
}

enum Status: String {
    case referred, invalid, member
}

我想对此类对象的数组进行排序,以便将所有成员保留在最后。

【问题讨论】:

    标签: arrays swift sorting


    【解决方案1】:

    这样做可以将所有成员保留在数组的末尾。其他元素保留原始顺序。

    contacts.sort(by: { c1, c2 in
        c2.status == .member
    })
    

    输出

    **Original array:**
    Anand referred
    Arti member
    Abid member
    Basha referred
    Bumrah member
    Catherine member
    Cambly invalid
    Faiz member
    Farnades referred
    Zebra member
    
    **New Array:**
    Anand referred
    Basha referred
    Cambly invalid
    Farnades referred
    Zebra member
    Faiz member
    Catherine member
    Bumrah member
    Abid member
    Arti member
    

    【讨论】:

    • 嗨@Faizyy,这是怎么回事,你在回答的同时回答了你的问题!?
    • @EgzonP。仅供参考,Stackoverflow 允许您通过同时为自己的问题提供答案来分享您的知识。我这样做主要是因为我找不到我的问题的答案,不得不自己弄清楚。以后可能会有其他人有同样的问题。
    • 嗨@Faizyy 我明白这一切,但你同时提出了问题和答案。我认为您应该在 Stackoverflow 中针对您不知道的事情提出问题。你这样做的方式最好是在 Medium 中创建博客文章或其他内容,因为如果我们都开始为“其他人可能需要”的东西提出问题和答案,我们将拥有一个巨大的地方,其中包含几乎不需要的东西和答案。再说一次,我问你这个是因为你在 09:25:35 0Z 提出问题,同时在 09:25:35 0Z 给出了答案。我强烈不建议你这样做!万事如意!
    • 排序不能保证原始数组的顺序会被保留,以防两个元素被认为相等。它可能适用于某些数据集,但对于其他数据集,它可能会以与输入数组中不同的顺序返回两个分区中的元素。
    • 更多,排序功能的标题文档说The sorting algorithm is not guaranteed to be stable. A stable sort preserves the relative order of elements that compare equal.。因此,不能保证使用 sort 会按照您的需要运行 (github.com/apple/swift/blob/main/stdlib/public/core/…)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多