按每个成员对结构数组进行排序

时间:2017-08-16 01:05:50

标签: arrays swift sorting struct

我正在使用以下结构编译数据:

struct Nursing {

var leftTime: Double
var rightTime: Double
var submissionTime: Date

}

struct Bottle {

var bottleQuantity: Double
var bottleUnits: String
var submissionTime: Date

}

struct Puree {

var pureeQuantity: Double
var pureeType: String
var pureeUnits: String
var submissionTime: Date

}

然后我使用应用程序中其他地方的数据创建每种类型的数组。

var nursingArray = [Nursing]()
var bottleArray = [Bottle]()
var pureeArray = [Puree]()

然后我只过滤每个数组,只查看最后一天发生的条目。

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
    var todayBottleArray = bottleArray.filter( { ( $0.submissionTime > yesterday! ) } )
    var todayNursingArray = nursingArray.filter( { ( $0.submissionTime > yesterday! ) } )
    var todayPureeArray = pureeArray.filter( { ( $0.submissionTime > yesterday! ) } )

最后,它们都被组合成一个未排序的数组。

    var unsortedTodayArray: [Any] = []

    unsortedTodayArray.append(todayBottleArray)
    unsortedTodayArray.append(todayNursingArray)
    unsortedTodayArray.append(todayPureeArray)

这是问题......虽然我知道它们是无关的,但submissionTime属性出现在所有三个中。如何按unsortedTodayArray排序submissionTime

1 个答案:

答案 0 :(得分:4)

您可以让您的结构符合相同的协议。有点像...

protocol SubmissionTimeable {
    var submissionTime: Date { get set }
}

struct Nursing: SubmissionTimeable {

    var leftTime: Double
    var rightTime: Double
    var submissionTime: Date
}

struct Bottle: SubmissionTimeable {

    var bottleQuantity: Double
    var bottleUnits: String
    var submissionTime: Date
}

struct Puree: SubmissionTimeable {

    var pureeQuantity: Double
    var pureeType: String
    var pureeUnits: String
    var submissionTime: Date
}

然后让你的未排序数组成为协议数组。

let unsortedArray = [SubmissionTimeable]()

然后你可以使用submissionTime对该数组进行排序。