我正在使用以下结构编译数据:
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
?
答案 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对该数组进行排序。