快速根据日期对混合对象类型的数组进行排序

时间:2019-02-07 23:02:09

标签: arrays swift

我有一个数组对象,每个对象至少包含一个Date类型的日期键

let arrayOfObjects: [Any] = [
    Cartoon(name: "Ben Ten", dateReleased: Date()),
    Milestone(dateReleased: Date()),
    Phone(color: "Black", dateReleased: Date())
]

我有这样一个数组,但具有更多混合对象数据类型。我想要的只是根据dateReleased以升序对对象数组进行升序排序。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

您可以定义一个需要单个protocol对象的Date,并使要排序的所有类型都符合该协议。然后,您需要将数组声明为[Released],然后只需在其上调用sorted

protocol Released {
    var dateReleased: Date { get }
}

struct Cartoon: Released {
    let name:String
    let dateReleased: Date
}

struct Milestone: Released {
    let dateReleased: Date
}

struct Phone: Released {
    let color:String
    let dateReleased: Date
}

let arrayOfObjects: [Released] = [
    Cartoon(name: "Ben Ten", dateReleased: Date()),
    Milestone(dateReleased: Date()),
    Phone(color: "Black", dateReleased: Date())
]

let sortedObjects = arrayOfObjects.sorted(by: {$0.dateReleased < $1.dateReleased})